first, simple to use
Copy the Code code as follows:
Def testlogbasic ():
Import logging
Logging.basicconfig (filename = ' Log.txt ', FileMode = ' a ', level = logging. NOTSET, format = '% (asctime) s-% (levelname) s:% (message) s ')
Logging.debug (' This is a message ')
Logging.info ("This is a info")
Logging.disable (#logging). WARNING
Logging.warning ("This is a warnning")
Logging.critical ("This is a critical issue")
Logging.error ("This is a error")
Logging.addlevelname ("Mycustomerror")
Logging.log ("This is a My custom error")
Try
Raise Exception (' This is a Exception ')
Except
Logging.exception (' exception ')
Logging.shutdown ()
Testlogbasic ()
Description: (This instance is the simplest use for logging log to a log file)
1) Logging.basicconfig () defines the default log to Log.txt,log file as append mode, which handles all logging,log of level greater than logging.notset defined as '% ' (asctime ) S-% (levelname) s:% (message) s ';
2) use Logging.debug () ... Log the corresponding level of log;
3) use Logging.disable () to disable a logging level;
4) Use Logging.addlevelname to add a custom logging level;
5) Use Logging.log to log custom logging level log;
The output text of the log is as follows:
Copy the Code code as follows:
2011-01-18 10:02:45,415-debug:this is a message
2011-01-18 10:02:45,463-info:this is a INFO
2011-01-18 10:02:45,463-critical:this is a CRITICAL issue
2011-01-18 10:02:45,463-error:this is a ERROR
2011-01-18 10:02:45,463-mycustomerror:this is a My custom error
2011-01-18 10:02:45,463-error:exception
Traceback (most recent):
File "testlog.py", line at Testlogbasic
Raise Exception (' This is a Exception ')
Exception:this is a Exception
Second, the level of logging
Copy the Code code as follows:
#logging level
#logging. NOTSET 0
#logging. DEBUG 10
#logging. INFO 20
#logging. WARNING 30
#logging. ERROR 40
#logging. CRITICAL 50
The level of the logging corresponds to an int, such as 10,20 ... the user can customize the level of the logging.
You can use Logging.setlevel () to specify the level of logger to be processed, such as my_logger.setlevel (logging. DEBUG) indicates that only logging of the level greater than 10 are processed for logging.
Third, handlers
Handler defines how log is stored and displayed.
Nullhandler don't do anything.
The Streamhandler instance sends an error to the stream (a file-like object).
The Filehandler instance sends an error to the disk file.
Baserotatinghandler is the base class for all round sacrifice logs and cannot be used directly. However, you can use Rotatingfilehandler and Timerotatingfilehandler.
The Rotatingfilehandler instance sends information to the disk file, and limits the maximum log file size, and the timing wheel sacrifice.
The Timerotatingfilehandler instance sends an error message to the disk and rounds the sacrifice at the appropriate event interval.
The Sockethandler instance sends the log to the TCP/IP socket.
The Datagramhandler instance sends an error message through the UDP protocol.
The Smtphandler instance sends an error message to a specific email address.
The Sysloghandler instance sends logs to the UNIX syslog service and supports the remote Syslog service.
The Nteventloghandler instance sends the log to the Windowsnt/2000/xp event log.
The Memoryhandler instance sends logs to the in-memory buffer and empties when certain conditions are reached.
The HttpHandler instance sends an error message to the HTTP server via the Get or post method.
Both the Nullhandler,streamhandler and Filehandler classes are defined in the core logging module. Other handler are defined in each sub-module, called Logging.handlers.
Of course, there is also a Logging.config module that provides configuration functionality.
Four, Filehandler + Streamhandler
Copy the Code code as follows:
Def testhanderandformat ():
Import logging
Logger = Logging.getlogger ("simple")
Logger.setlevel (logging. DEBUG)
# Create file handler which logs even debug messages
FH = logging. Filehandler ("Simple.log")
Fh.setlevel (logging. DEBUG)
# Create console handler with a higher log level
ch = logging. Streamhandler ()
Ch.setlevel (logging. ERROR)
# Create formatter and add it to the handlers
Formatter = logging. Formatter ("% (asctime) s-% (name) s-% (levelname) s-% (message) s")
Ch.setformatter (Formatter)
Fh.setformatter (Formatter)
# Add the handlers to logger
Logger.addhandler (CH)
Logger.addhandler (FH)
# "Application" code
Logger.debug ("Debug Message")
Logger.info ("info message")
Logger.warn ("Warn message")
Logger.error ("error message")
Logger.critical ("critical Message")
Testhanderandformat ()
Description: (this instance uses both Filehandler and Streamhandler to write log to file and console simultaneously)
1) use Logging.getlogger () to create a new named logger;
2) Use logging. Filehandler () to generate Filehandler to write log to the log file, using Logger.addhandler () to bind handler with logger;
3) Use logging. Streamhandler () to generate Streamhandler to write log to the console, using Logger.addhandler () to bind handler with logger;
4) Use logging. Formatter () Constructs an instance of the log format, using Handler.setformatter () to bind Formatter with handler;
Run results
Simple.txt
Copy the Code code as follows:
2011-01-18 11:25:57,026-simple-debug-debug Message
2011-01-18 11:25:57,072-simple-info-info Message
2011-01-18 11:25:57,072-simple-warning-warn Message
2011-01-18 11:25:57,072-simple-error-error Message
2011-01-18 11:25:57,072-simple-critical-critical Message
Console
Copy the Code code as follows:
2011-01-18 11:25:57,072-simple-error-error Message
2011-01-18 11:25:57,072-simple-critical-critical Message
Wu, Rotatingfilehandler
Copy the Code code as follows:
Def testrotating ():
Import Glob
Import logging
Import Logging.handlers
Log_filename = ' Logging_rotatingfile_example.out '
# Set up a specific logger with we desired output level
My_logger = Logging.getlogger (' MyLogger ')
My_logger.setlevel (logging. DEBUG)
# ADD The log message handler to the logger
Handler = Logging.handlers.RotatingFileHandler (Log_filename, maxbytes=20, backupcount=5)
My_logger.addhandler (Handler)
# Log Some messages
For I in range (20):
My_logger.debug (' i =%d '% i)
# What's the files are created
LogFiles = Glob.glob ('%s* '% log_filename)
For filename in logfiles:
Print (filename)
Testrotating ()
Description
Rotatingfilehandler Specifies the maximum size of a single log file and the maximum number of log files, if the file is larger than the maximum value, it will be split into multiple files, and if the log file has more than the maximum number, the oldest log file will be deleted. For example, the newest log in this example always contains the oldest log in the logging_rotatingfile_example.out,logging_rotatingfile_example.out.5.
Operation Result:
Copy the Code code as follows:
Logging_rotatingfile_example.out
Logging_rotatingfile_example.out.1
Logging_rotatingfile_example.out.2
Logging_rotatingfile_example.out.3
Logging_rotatingfile_example.out.4
Logging_rotatingfile_example.out.5
Vi. use of fileconfig to use logger
Copy the Code code as follows:
Import logging
Import Logging.config
Logging.config.fileConfig ("logging.conf")
# Create Logger
Logger = Logging.getlogger ("Simpleexample")
# "Application" code
Logger.debug ("Debug Message")
Logger.info ("info message")
Logger.warn ("Warn message")
Logger.error ("error message")
Logger.critical ("critical Message")
The logging.conf file is as follows:
Copy the Code code as follows:
[Loggers]
Keys=root,simpleexample
[Handlers]
Keys=consolehandler
[Formatters]
Keys=simpleformatter
[Logger_root]
Level=debug
Handlers=consolehandler
[Logger_simpleexample]
Level=debug
Handlers=consolehandler
Qualname=simpleexample
Propagate=0
[Handler_consolehandler]
Class=streamhandler
Level=debug
Formatter=simpleformatter
Args= (Sys.stdout,)
[Formatter_simpleformatter]
format=% (asctime) s-% (name) s-% (levelname) s-% (message) s
datefmt=
Operation Result:
Copy the Code code as follows:
2005-03-19 15:38:55,977-simpleexample-debug-debug Message
2005-03-19 15:38:55,979-simpleexample-info-info Message
2005-03-19 15:38:56,054-simpleexample-warning-warn Message
2005-03-19 15:38:56,055-simpleexample-error-error Message
2005-03-19 15:38:56,130-simpleexample-critical-critical Message