Create a logging log file in Python

Source: Internet
Author: User
ArticleDirectory
    • Four main components
    • Log Level
    • Logging. basicconfig ([** kwargs]):
    • Logging. setloggerclass (Klass)
    • Logging. getloggerclass ()
    • Logging. getlevelname (LVL)
    • Logging. Shutdown ()
    • Logger. Exception (MSG [, * ARGs])
    • Logger. addfilter (filt)
    • Logger. removefilter (filt)
    • Logger. addhandler (hdlr)
    • Logger. removehandler (hdlr)
    • Logger. makerecord (name, LVL, FN, lno, MSG, argS, exc_info [, func, extra])

Many applicationsProgramThe log module is used to record some key information of the system during operation, so as to track the running status of the system. In. on the Net platform, there is a well-known third-party open-source log component log4net, C ++, and a familiar log4cpp. in Python, we do not need third-party log components, because it has provided us with a simple and powerful Log Module: logging. The logging module allows you to save log information to different target domains, for example, to log files, and send log information by email; submit logs to the web server in the form of http get or post, and record logs in the form of Windows events. These log storage methods can be used in combination. You can set your own log level and log format for each method. The Log Module has a lot of content. Today, we will first learn about the basic usage of the logging module, and next time we will learn about how to process logs.

Let's take a look at a simple example to give us a perceptual knowledge of the logging module:

    1. ImportLogging
    2. Logging. basicconfig (filename = OS. Path. Join (OS. getcwd (),'Log.txt'), Level = logging. Debug)
    3. Logging. debug ('This is a message')

Import logging. basicconfig (filename = OS. path. join (OS. getcwd (), 'log.txt '), Level = logging. debug) logging. debug ('this is a message ')

RunCodeA log.txt file will be created under the program's root directory to open the file with a log record: "Debug: Root: this is a message ".

Four main components

Logger: log class. Applications often call the APIS provided by logger to record logs;

Handler: Process log information and send (SAVE) logs to different target domains;

Filter: filter log information;

Formatter: format the log;

Log Level

When logging, log messages are associated with a level ("level" is essentially a non-negative integer ). By default, the system provides six levels:

Level Corresponding value
Critical 50
Error 40
Warning 30
Info 20
Debug 10
Notset 0

You can set the log level for the log object (logger instance). log messages lower than this level will be ignored, or you can set the log level for hanlder. For log messages lower than this level, handler will also ignore.

Common functions in the logging module:

Logging. basicconfig ([** kwargs]):

Configure basic information for the log module. Kwargs supports the following keyword parameters:
Filename: Path for saving log files. If some parameters are configured, A filehandler is automatically created as the handler;
Filemode: Log File opening mode. The default value is 'A', indicating that the log message is appended to the log file. If it is set to 'w', a new log file will be created every time the program starts;
Format: Set the log output format;
Datefmt: Defines the date format;
Level: Set the log level. log messages lower than this level will be ignored;
Stream: Set a specific stream to initialize streamhandler;

The following is a simple example:

  1. # Coding = GBK
  2. ImportLogging
  3. Logging. basicconfig (filename = OS. Path. Join (OS. getcwd (),'Log.txt'),\
  4. Level = logging. Warn, filemode ='W', Format ='% (Asctime) S-% (levelname) S: % (Message) s')
  5. Logging. debug ('Debug')# Ignored
  6. Logging.info ('Info')# Ignored
  7. Logging. Warning ('Warn')
  8. Logging. Error ('Error')
  9. # ----- Result
  10. #21:42:15, 592-warning: warn
  11. #21:42:15, 640-error: Error

# Coding = GBK import logging. basicconfig (filename = OS. path. join (OS. getcwd (), 'log.txt '), \ level = logging. warn, filemode = 'w', format = '% (asctime) S-% (levelname) S: % (Message) s') logging. debug ('debug') # ignored logging.info ('info') # ignored logging. warning ('warn') logging. error ('error') # ----- result #21:42:15, 592-warning: Warn #21:42:15, 640-error: Error

Logging. getlogger ([name])

Create a logger object. Logger objects are used to record logs. You must provide the logger name when calling getlogger (Note: The same name is used to call getlogger multiple times, and a reference to the same object is returned .), There is a hierarchical relationship between logger instances. These relationships are reflected by the logger name, for example:

P = logging. getlogger ("root ")

C1 = logging. getlogger ("root. C1 ")

C2 = logging. getlogger ("root. C2 ")

In this example, p is the parent logger, C1, and c2 are the sub-logger of P. C1 and C2 inherit the settings of P. If the name parameter is omitted, getlogger returns the root logger in the log object hierarchy.

Logging. setloggerclass (Klass) logging. getloggerclass ()

Obtain/set the log type. You can customize the log class to replace the logging. Logger class provided by the system.

Logging. getlevelname (LVL)

Obtain the name corresponding to the log level. For example:

  1. PrintLogging. getlevelname (logging. notset)
  2. PrintLogging. getlevelname (10)# Logging. Debug
  3. PrintLogging. getlevelname (logging. Debug)
  4. PrintLogging. getlevelname (30)# Logging. Warn
  5. PrintLogging. getlevelname (logging. Error)
  6. PrintLogging. getlevelname (50)# Logging. Critical

Print logging. getlevelname (logging. notset) print logging. getlevelname (10) # logging. debug print logging. getlevelname (logging. debug) print logging. getlevelname (30) # logging. warn print logging. getlevelname (logging. error) print logging. getlevelname (50) # logging. critical

Logging. Shutdown ()

When the log system is no longer used, this method is called, and the log is flushed to the corresponding target domain. It is generally called when the system exits.

Logger objectBy callingLogging. getlogger (name) is created. It has the following common methods and attributes:

Logger. setlevel (LVL ):

Set the log level. Log messages lower than this level are ignored. The following example demonstrates the setlevel method:

  1. # Coding = GBK
  2. Import Logging
  3. Logging. basicconfig (filename = OS. Path. Join (OS. getcwd (),'Log.txt'), Level = logging. Debug)
  4. Log = logging. getlogger ('Root. Test')
  5. Log. setlevel (logging. Warn) # The log record level is warnning.
  6. Log.info ('Info') # Not recorded
  7. Log. debug ('Debug') # Not recorded
  8. Log. Warning ('Warnning')
  9. Log. Error ('Error')

# Coding = GBK import logging. basicconfig (filename = OS. path. join (OS. getcwd (), 'log.txt '), Level = logging. debug) log = logging. getlogger ('root. test') log. setlevel (logging. warn) # The log record level is warnning log.info ('info') # logs are not recorded. debug ('debug') # logs are not recorded. warning ('warning') log. error ('error ')

Logger. debug (msg [ , * ARGs [, ** kwargs ])

Logs at the debug level. The msg parameter is the information format, and The args and kwargs parameters are the format parameters respectively.

  1. ImportLogging
  2. Logging. basicconfig (filename = OS. Path. Join (OS. getcwd (),'Log.txt'), Level = logging. Debug)
  3. Log = logging. getlogger ('Root')
  4. Log. debug ('% S, % s, % s',*('Error','Debug','Info'))
  5. Log. debug ('% (Module) s, % (Info) s',{'Module':'Log','Info':'Error'})

Import logging. basicconfig (filename = OS. path. join (OS. getcwd (), 'log.txt '), Level = logging. debug) log = logging. getlogger ('root') log. debug ('% s, % s, % s', * ('error', 'debug', 'info') log. debug ('% (module) s, % (Info) s', {'module': 'log', 'info': 'error '})

Logger.info (msg [ , * ARGs [ , ** Kwargs ] ] ) Logger. warnning (msg [ , * ARGs [ , ** Kwargs ] ] ) Logger. Error (msg [ , * ARGs [ , ** Kwargs ] ] ) Logger. Critical (msg [ , * ARGs [ , ** Kwargs ] ] )

Record log information of the corresponding level. The parameter has the same meaning as logger. debug.

Logger. Log (LVL, MSG [ , * ARGs [ , ** Kwargs ] ] )

Logs are recorded. The LVL user sets the log information level. The parameter MSG, * ARGs, ** kwargs has the same meaning as logger. debug.

Logger. Exception (MSG [, * ARGs])

Log messages are recorded at the error level. Exception tracking information is automatically added to log messages. Logger. exception is used in exception handling blocks, for example:

    1. Import logging
    2. logging. basicconfig (filename = OS. path. join (OS. getcwd (), 'log.txt ' ), Level = logging. debug)
    3. log = logging. getlogger ( 'root' )
    4. try :
    5. raise exception, 'this is a exception'
    6. skip T :
    7. log. exception ( 'exception' ) # The exception information is automatically added to the log message.

Import logging. basicconfig (filename = OS. path. join (OS. getcwd (), 'log.txt '), Level = logging. debug) log = logging. getlogger ('root') Try: Raise exception, 'This is a exception' handle T: log. exception ('exception') # The exception information is automatically added to the log message.

Logger. addfilter (filt) Logger. removefilter (filt)

Add/Remove a log message filter. This section describes filter in detail.

Logger. addhandler (hdlr) Logger. removehandler (hdlr)

Add/Remove a log message processor. This section describes handler in detail.

Logger. makerecord (name, LVL, FN, lno, MSG, argS, exc_info [, func, extra])

Create a logrecord object. A log message is taken as a logrecord object and processed in the log class.

 

Reproduced in: http://blog.csdn.net/jgood/archive/2009/07/11/4340740.aspx

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.