Simple encapsulation of Python's logging example

Source: Internet
Author: User

With Python's logging, every time you write a log, you make a small module to make the log more convenient.
The code is as follows

log.py


Import Logging, Logging.handlers
Import Config
Import Inspect

FORMAT = '% (asctime) s-% (name) s-% (levelname) s-% (message) s '
Log_level = logging. DEBUG
Logger = {}
Handler = Logging.handlers.RotatingFileHandler (
Config. Path_log_file,
MaxBytes = 1048576 * 2, # 2MB
Backupcount = 5,
)
Handler.setformatter (logging. Formatter (FORMAT))

__all__ = [' Log ', ' logi ', ' LogE ', ' logd ', ' logc ', ' LOGW ']
def Log (name):
    if Inspect.isclass ( Type (name): #instance
        name = name.__class__.__name__
     elif Inspect.isclass (type (name)): #class
        name = name.__ name__
    Else:
        name = name or "No_name"
 & nbsp;  if name in logger:
        return logger[name]
     Else:
        l = Logging.getlogger (name)
         l.setlevel (log_level)
        L.addhandler (handler)
        Logger[name] = l
        return L

Def logi (name, log):
Return log (name). info (log)

def LogE (name, log):
Return log (name). Error (log)

def logd (name, log):
Return log (name). Debug (log)

def logc (name, log):
Return log (name). Critical (log)

def LOGW (name, log):
Return log (name). Warning (log)


Try:


From log import *

Class C (object):
def logc (self, log):
LOGC (self, log)

Instance = C ()
Logi (C (), ' passing instance ')
LOGW (C, ' passing class type ')
INSTANCE.LOGC ("Passing Self")

Take a look at our log output:

2014-12-06 15:10:56,817-c-info-passing Instance
2014-12-06 15:10:56,818-type-warning-passing class type
2014-12-06 15:10:56,818-c-critical-passing self

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.