1. Simply print logs to the screen
importlogging
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')
Screen Printing:
WARNING: root: This is warning message
By default, logging prints logs to the screen at the Log Level of WARNING;
The log level relationship is: CRITICAL> ERROR> WARNING> INFO> DEBUG> NOTSET. You can also define the log level by yourself.
2. Use the logging. basicConfig function to configure the log output format and method.
importlogging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='myapp.log',
filemode='w')
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')
The./myapp. log file contains the following content:
Sun, 24 May 2009 21:48:54 demo2.py [line: 11] DEBUG This is debug message
Sun, 24 May 2009 21:48:54 demo2.py [line: 12] INFO This is info message
Sun, 24 May 2009 21:48:54 demo2.py [line: 13] WARNING This is warning message
Parameters of the logging. basicConfig function:
Filename: Specifies the log file name.
Filemode: Same as the file function. It specifies the log file opening mode, 'w' or 'A'
Format: Specify the output format and content. format can output a lot of useful information, as shown in the preceding example:
% (Levelno) s: print the log-level value
% (Levelname) s: print the Log Level name
% (Pathname) s: print the path of the current execution program, which is actually sys. argv [0]
% (Filename) s: print the name of the currently executed Program
% (FuncName) s: current function for printing logs
% (Lineno) d: print the current line number of the log
% (Asctime) s: log printing time
% (Thread) d: Print thread ID
% (ThreadName) s: print the thread name
% (Process) d: print the process ID
% (Message) s: Print log information
Datefmt: specifies the time format, which is the same as time. strftime ()
Level: Set the log level. The default value is logging. WARNING.
Stream: Specifies the output stream of logs. You can specify the output stream to sys. stderr, sys. stdout or file, which is output to sys by default. stderr. When stream and filename are both specified, stream is ignored.
3. Output logs to both files and screens.
Importlogging
Logging. basicConfig (level = logging. DEBUG,
Format = '% (asctime) s % (filename) s [line: % (lineno) d] % (levelname) s % (message) s ',
Datefmt = '% a, % d % B % Y % H: % M: % s ',
Filename = 'myapp. log ',
Filemode = 'W ')
######################################## ######################################## #################
# Define a StreamHandler to print INFO-level or higher log information to a standard error and add it to the current log processing object #
Console = logging. StreamHandler ()
Console. setLevel (logging. INFO)
Formatter = logging. Formatter ('% (name)-12 s: % (levelname)-8 s % (message) s ')
Console. setFormatter (formatter)
Logging. getLogger (''). addHandler (console)
######################################## ######################################## #################
Logging. debug ('this is debug message ')
Logging.info ('this is info message ')
Logging. warning ('this is warning message ')
Screen Printing:
Root: INFOThis is info message
Root: WARNINGThis is warning message
The./myapp. log file contains the following content:
Sun, 24 May 2009 21:48:54 demo2.py [line: 11] DEBUG This is debug message
Sun, 24 May 2009 21:48:54 demo2.py [line: 12] INFO This is info message
Sun, 24 May 2009 21:48:54 demo2.py [line: 13] WARNING This is warning message
4. Log rollback with logging
Importlogging
Fromlogging. handlersimportRotatingFileHandler
######################################## ######################################## #################
# Define a RotatingFileHandler to back up to five log files, each of which is up to 10 MB
Rthandler = RotatingFileHandler ('myapp. log', maxBytes = 10*1024*1024, backupCount = 5)
Rthandler. setLevel (logging. INFO)
Formatter = logging. Formatter ('% (name)-12 s: % (levelname)-8 s % (message) s ')
Rthandler. setFormatter (formatter)
Logging. getLogger (''). addHandler (Rthandler)
######################################## ######################################## ################
From the above example, we can see that logging has a main log processing object. Other processing methods are added through addHandler.
Several handle methods of logging are as follows:
Logging. StreamHandler: logs are output to the stream, which can be sys. stderr, sys. stdout, or files.
Logging. FileHandler: logs are output to files.
Log rollback method. RotatingFileHandler and TimedRotatingFileHandler are used in actual use.
Logging. handlers. BaseRotatingHandler
Logging. handlers. RotatingFileHandler
Logging. handlers. TimedRotatingFileHandler
Logging. handlers. SocketHandler: remotely outputs logs to TCP/IP sockets
Logging. handlers. DatagramHandler:Remotely output logs to UDP sockets
Logging. handlers. SMTPHandler:Remotely output logs to the email address
Logging. handlers. SysLogHandler: syslog output
Logging. handlers. NTEventLogHandler: remotely outputs Event Logs to Windows NT/2000/XP.
Logging. handlers. MemoryHandler: the buffer used to output logs to the memory.
Logging. handlers. HTTPHandler: Remote output to the HTTP server through "GET" or "POST"
Because StreamHandler and FileHandler are common log processing methods, they are directly included in the logging module, while other methods are included in the logging. handlers module,
For more information about how to use the above processing methods, see the python2.5 manual!
5. Configure logs through the logging. config module
#logger.conf
###############################################
[loggers]
keys=root,example01,example02
[logger_root]
level=DEBUG
handlers=hand01,hand02
[logger_example01]
handlers=hand01,hand02
qualname=example01
propagate=0
[logger_example02]
handlers=hand01,hand03
qualname=example02
propagate=0
###############################################
[handlers]
keys=hand01,hand02,hand03
[handler_hand01]
class=StreamHandler
level=INFO
formatter=form02
args=(sys.stderr,)
[handler_hand02]
class=FileHandler
level=DEBUG
formatter=form01
args=('myapp.log', 'a')
[handler_hand03]
class=handlers.RotatingFileHandler
level=INFO
formatter=form02
args=('myapp.log', 'a', 10*1024*1024, 5)
###############################################
[formatters]
keys=form01,form02
[formatter_form01]
format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s
datefmt=%a, %d %b %Y %H:%M:%S
[formatter_form02]
format=%(name)-12s: %(levelname)-8s %(message)s
datefmt=
Example 3:
importlogging
importlogging.config
logging.config.fileConfig("logger.conf")
logger=logging.getLogger("example01")
logger.debug('This is debug message')
logger.info('This is info message')
logger.warning('This is warning message')
Example 4:
importlogging
importlogging.config
logging.config.fileConfig("logger.conf")
logger=logging.getLogger("example02")
logger.debug('This is debug message')
logger.info('This is info message')
logger.warning('This is warning message')
6. logging is thread-safe.
From: http://blog.csdn.net/yatere/article/details/6655445