Pythonlogging class library example

Source: Internet
Author: User
This article describes how to use the pythonlogging class library. This article describes simple usage, logging level, Handlers, FileHandler + StreamHandler, and so on. For more information, see I. simple use

The code is 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 (30) # logging. WARNING
Logging. warning ("this is a warnning ")
Logging. critical ("this is a critical issue ")
Logging. error ("this is a error ")
Logging. addLevelName (88, "MyCustomError ")
Logging. log (88, "this is an my custom error ")
Try:
Raise Exception ('This is a exception ')
Except t:
Logging. exception ('exception ')
Logging. shutdown ()

TestLogBasic ()

Note: (This instance is the simplest method to record logs to log files)

1. logging.basicconfig(define the specific logto log.txt in logging, and the log file is in append mode. process all levels greater than logging. NOTSET logging. the log format is defined as '% (asctime) s-% (levelname) s: % (message) s ';

2) use logging. debug ()... to log the corresponding level;

3) use logging. disable () to disable a certain logging level;

4) use logging. addLevelName to increase the Custom logging level;

5) use logging. log to log custom logging level logs;

The output text log is as follows:

The code is as follows:


10:02:45, 415-DEBUG: this is a message
10:02:45, 463-INFO: this is a info
10:02:45, 463-CRITICAL: this is a critical issue
10:02:45, 463-ERROR: this is a error
10:02:45, 463-MyCustomError: this is an my custom error
10:02:45, 463-ERROR: exception
Traceback (most recent call last ):
File "testlog. py", line 15, in TestLogBasic
Raise Exception ('This is a exception ')
Exception: this is a exception

2. logging level

The code is as follows:


# Logging level
# Logging. NOTSET 0
# Logging. DEBUG 10
# Logging. INFO 20
# Logging. WARNING 30
# Logging. ERROR 40
# Logging. CRITICAL 50

The logging level corresponds to an int, such as 10, 20... you can customize the logging level.

You can use logging. setLevel () to specify the logger level to be processed. for example, my_logger.setLevel (logging. DEBUG) indicates that only logging with a level greater than 10 can be processed.

3. Handlers

Handler defines the storage and display methods of logs.

NullHandler does not do anything.

The StreamHandler instance sends an error to the stream (object similar to a file ).
The FileHandler instance sends an error to the disk file.
BaseRotatingHandler is the base class of all round worker logs and cannot be used directly. However, you can use RotatingFileHandler and TimeRotatingFileHandler.
The RotatingFileHandler instance sends information to the disk file, limits the maximum size of the log file, and rounds the rolling process in due time.
The TimeRotatingFileHandler instance sends an error message to the disk and performs round-robin at an appropriate event interval.
The SocketHandler instance sends logs to the TCP/IP socket.
The rabbitramhandler instance sends an error message through 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 remote syslog service.
The NTEventLogHandler instance sends logs to WindowsNT/2000/XP event logs.
The MemoryHandler instance sends logs to the buffer in the memory and clears the logs when the specified conditions are met.
The HTTPHandler instance sends an error message to the HTTP server through the GET or POST method.
The NullHandler, StreamHandler, and FileHandler classes are defined in the core logging module. Other handler is defined in each sub-module, called logging. handlers.

Of course, there is also a logging. config module that provides the configuration function.

IV. FileHandler + StreamHandler

The code is 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 ()

Note: (This instance uses both FileHandler and StreamHandler to write logs to both files and the console)

1) use logging. getLogger () to create a new logger name;

2) use logging. FileHandler () to generate FileHandler to write logs into the log file. use logger. addHandler () to bind the handler with logger;

3) use logging. StreamHandler () to generate StreamHandler to write the log to the console. use logger. addHandler () to bind the handler with logger;

4) use logging. Formatter () to construct an instance in log format, and use handler. setFormatter () to bind the formatter to the handler;

Running result

Simple.txt

The code is as follows:


11:25:57, 026-simple-DEBUG-debug message
11:25:57, 072-simple-INFO-info message
11:25:57, 072-simple-WARNING-warn message
11:25:57, 072-simple-ERROR-error message
11:25:57, 072-simple-CRITICAL-critical message

Console

The code is as follows:


11:25:57, 072-simple-ERROR-error message
11:25:57, 072-simple-CRITICAL-critical message

5. RotatingFileHandler

The code is as follows:


Def TestRotating ():
Import glob
Import logging
Import logging. handlers

LOG_FILENAME = 'logging _ rotatingfile_example.out'

# Set up a specific logger with our 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)

# See what files are created
Logfiles = glob. glob ('% s *' % LOG_FILENAME)

For filename in logfiles:
Print (filename)

TestRotating ()

Note:

RotatingFileHandler specifies the maximum size of a single log file and the maximum number of log files. if the file is greater than the maximum size, it is divided into multiple files. if the number of log files is greater than the maximum number, the oldest log file will be deleted. For example, the latest log in this example always contains the oldest log in logging_rotatingfile_example.out and logging_rotatingfile_example.out.5.

Running result:

The code is 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

6. use fileConfig to use logger

The code is 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:

The code is 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 =

Running result:

The code is as follows:


15:38:55, 977-simpleExample-DEBUG-debug message
2005-03-19 15:38:55, 979-simpleExample-INFO-info message
15:38:56, 054-simpleExample-WARNING-warn message
15:38:56, 055-simpleExample-ERROR-error message
15:38:56, 130-simpleExample-CRITICAL-critical message

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.