Giter VIP home page Giter VIP logo

python-logging-template's Introduction

python-logging-template

Python logging template using dictConfig

Reference

Configuration

logging_config.py

import logging
import datetime
import time

class UTCFormatter(logging.Formatter):
    converter = time.gmtime


class RotatingFileNameHandler(logging.handlers.RotatingFileHandler):
    def __init__(self, filename, logPath):

        # set format type
        formatter = logging.Formatter(fmt="%(asctime)s - PID: %(process)d"\
                                        " - %(levelname)s - %(filename)s - %(message)s",
                                      datefmt="%Y-%m-%d %I:%M:%S %p")

        # set filename by the name of scripts
        logPath = logPath + "/" + filename.split('.')[0] + ".log"

        # please set the maxBytes by yourself
        # it will backup three files and delete the oldest one when create a new one
        super(RotatingFileNameHandler, self).__init__(filename=logPath, maxBytes=1024, backupCount=3)
        super(RotatingFileNameHandler, self).setFormatter(fmt=formatter)

        # NOTSET, DEBUG, INFO, WARNING, ERROR, CRITICAL
        super(RotatingFileNameHandler, self).setLevel(logging.INFO)

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        # local time
        "standard": { 
            "format": "%(asctime)s - %(message)s",
            "datefmt": "%Y-%m-%d %I:%M:%S %p"
        },
        "complete": {
            "format": "%(asctime)s - PID: %(process)d"\
                      " - %(levelname)s - %(filename)s - %(message)s",
            "datefmt": "%Y-%m-%d %I:%M:%S %p"
        },
        "utc": {
            # "()" is a special key, which indicates a custom instantiation.
            "()": UTCFormatter,
            "format": "%(asctime)s %(message)s",
            "datefmt": "%Y-%m-%d %I:%M:%S %p"
        }
    },
    "handlers": {
        # StreamHandler will show log in console
        "default": { 
            "level": "INFO",
            "formatter": "complete",
            "class": "logging.StreamHandler"
        }
    },
    # root logger
    "root": {
        "handlers": ["default"],
        "level": "INFO",
        "propagate": True
    }
}

Test File

testLogger.py

import logging
import logging.config
import logging_config
from logging_config import RotatingFileNameHandler

logging.config.dictConfig(logging_config.LOGGING)

# create logger
logger = logging.getLogger()
logger.addHandler(RotatingFileNameHandler(__file__, "./log"))

# "application" code
logger.debug("debug message")
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("critical message")

test output from testLogger.py

2018-06-27 03:58:15 PM - PID: 68496 - INFO - testLogger.py - info message
2018-06-27 03:58:15 PM - PID: 68496 - WARNING - testLogger.py - warn message
2018-06-27 03:58:15 PM - PID: 68496 - ERROR - testLogger.py - error message
2018-06-27 03:58:15 PM - PID: 68496 - CRITICAL - testLogger.py - critical message

python-logging-template's People

Contributors

huanglipang avatar quenlo avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.