Home  >  Article  >  Backend Development  >  python module learning logging

python module learning logging

黄舟
黄舟Original
2016-12-17 16:47:11934browse

1. Simply print the log to the screen

import logging

logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message' )



Print on the screen:
WARNING:root:This is warning message

By default, logging prints the log to the screen, the log level is WARNING;
The log level size relationship is: CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET. Of course, you can also define the log level yourself.

2. Configure the log output format and method through the logging.basicConfig function

import logging

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',
                   ', I filemode =' w ')
Logging.debug (' This is debug message ')
logging.info (' this is inco message ')
logging.warning (' this is warning m essage ') g



The content in the ./myapp.log file is:
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 logging.basicConfig function:

filename: Specify the log file name

filemode: It has the same meaning as the file function, specifying the opening mode of the log file, 'w' or 'a'
format: Specify the format and content of the output. format can output a lot of useful information, as shown in the above example:
%(levelno)s: Print the value of the log level
%(levelname)s: Print the log level name
%(pathname)s: Print the path of the currently executing program, which is actually sys.argv[0]
%(filename)s: Print the current executing program name
%(funcName)s: Print the current function of the log
%(lineno)d: Print the current line number of the log
%(asctime)s: Time to print log
%(thread)d: Print thread ID
%(threadName)s: Print thread name
%(PRocess)d: Print process ID
%(message)s: Print log information
datefmt: Specify the time format, the same as time.strftime()
level: Set the log level, the default is logging.WARNING
stream: Specify the output stream of the log. You can specify the output to sys.stderr, sys.stdout or a file. The default output is to sys.stderr. When stream and filename are specified at the same time, the stream is ignored. 3. Output the log to the file and file at the same time. Screen

import logging

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 INFO level or higher Log information is printed to standard error and added to the current log processing object #console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)-12s: % (levelname)-8s %(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')



Print on screen:
root : INFO This is info message
root : WARNING This is warning message

./myapp.log file The content is:
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.logging log rollback

import loggingfrom logging.handlers import RotatingFileHandler######################################## ################################################# ######Define a RotatingFileHandler to back up up to 5 log files, each log file has a maximum of 10MRthandler = RotatingFileHandler('myapp.log', maxBytes=10*1024*1024, backupCount=5)
Rthandler.setLevel(logging .INFO)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
Rthandler.setFormatter(formatter)
logging.getLogger('').addHandler(Rthandler )############################################### #############################################

As can be seen from the above example and this example, logging has a main object for log processing, and other processing methods are added through addHandler.
The several handle methods for logging are as follows:

logging.StreamHandler: The log is output to a stream, which can be sys.stderr, sys.stdout or a file. logging.FileHandler: The log is output to a file

Log rollback method. In actual use, RotatingFileHandler and TimedRotatingFileHandler are used logging.handlers.BaseRotatingHandler logging.handlers.RotatingFileHandler logging.handlers.TimedRotatingFileHandler

logging.handlers.SocketHandler: Remotely output logs to TCP/ip sockets

logging.handlers.DatagramHandler: Remote output logs to UDP sockets

logging.handlers.SMTPHandler: Remotely output logs to email address

logging.handlers.SysLogHandler: Log output to syslog

logging.handlers.NTEventLogHandler: Remotely output logs to the event log of Windows NT/2000/XP

logging.handlers.MemoryHandler: The log is output to the specified buffer in memory

logging.handlers.HTTPHandler: Remote output to HTTP server through "GET" or "POST"

Since StreamHandler and FileHandler are commonly used log processing methods, they are directly included in the logging module, while other methods are included in the logging.handlers module,
Above For other processing methods, please refer to 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=
import loggingimport logging.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')
import loggingimport logging.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

The above is the content of learning logging in the python module. For more related articles, please pay attention to the PHP Chinese website (www.php .cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn