The correct way to open python3 output log (1)

    There are generally two forms of log output in python, one is to simply output to the terminal, and the other is to save to a file, and there are many ways to choose these log forms.

1. The easiest way

        print("testtesttest")


2、使用logging.config.fileConfig()

      The way of using configuration files can separate log configuration and code, which facilitates code maintenance and independent log management, and is more flexible.

    Create configuration file

     To use logging.config.fileConfig(), first create a configuration file, such as log.conf, and add the following content.

#log.conf

###################keys#########################
[loggers]
keys=root,file,fileAndConsole,rotatingFile

[handlers]
keys=consoleHandler,timedRotatingFileHandler,rotatingFileHandler

[formatters]
keys=simpleFormatter

###################logger#########################
[logger_root]
level=DEBUG
handlers=consoleHandler

[logger_file]
level=DEBUG
handlers=timedRotatingFileHandler
qualname=file
propagate=0

[logger_fileAndConsole]
level=DEBUG
handlers=consoleHandler,timedRotatingFileHandler
qualname=fileAndConsole
propagate=0

[logger_rotatingFile]
level=DEBUG
handlers=rotatingFileHandler
qualname=rotatingFile
propagate=0

###################handler#########################
[handler_consoleHandler]
class=StreamHandler
args=(sys.stdout,)
level=DEBUG
formatter=simpleFormatter

#
[handler_timedRotatingFileHandler]
class=handlers.TimedRotatingFileHandler
args=('/log/app.log', 'D', 1, 31)
level=DEBUG
formatter=simpleFormatter

#
[handler_rotatingFileHandler]
class=handlers.RotatingFileHandler
args=('log/app2.log', 'a', 20 * 1024 * 1024, 10)
level=DEBUG
formatter=simpleFormatter

###################formatter#########################
[formatter_simpleFormatter]
format=%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s
datefmt=%Y-%m-%d %H:%M:%S

        Configuration file description

        1. In the above configuration file, there are three major modules to be used for logging, loggers, handlers, and formatters. The contents of the three modules are specified by keys, and then the keys inside are specifically configured through logger_key/handler_key/formatter_key.

        2. The logger module configured for loggers must contain a logger called root. If the parameterless function logging.getLogger() is used in the application, the root logger is returned by default, and other custom loggers pass logging .getLogger("name") Set accordingly.

       3. The handlers configuration is the handlers module, which is also specified by keys. You can set the log output mode, log level, log format, etc. in it.

       4. The formatters configure the format of the log content.

       5. logger_*** configures the loggers declared in loggers one by one, and must have a one-to-one correspondence. In all loggers, the level and handlers options must be set. For non-root handlers, add additional options

  • handlers: You can specify multiple, separated by commas, such as handlers=consoleHandler,timedRotatingFileHandler, and set the console and file output log at the same time
  • qualname: Indicates its name in the logger hierarchy. The handler used is found through this name in the application code, namely logging.getLogger("fileAndConsole").
  • propagate: Usually set to zero. When multiple processors are set in handlers, the log information will not be printed multiple times.

 

        6. handler_*** in the handler, the class and args options must be specified

        Commonly used classes include:

  • logging.StreamHandler may be similar to the sys.stdout or sys.stderr any object file (file object) output
  • logging.FileHandler is used to output log information to a file
  • logging.handlers.RotatingFileHandler is similar to the FileHandler above , but it can manage file size. When the file reaches a certain size, it will automatically rename the current log file, and then create a new log file with the same name to continue output
  • logging.handlers.TimedRotatingFileHandler and RotatingFileHandler similar, but it does not have to decide when to re-create the log file to determine the file size, but a certain time interval automatically create a new log file

Parameter meaning and sequence:

  • logging.handlers.SocketHandler uses TCP protocol to send log information to the network.
  • logging.handlers.DatagramHandler uses UDP protocol to send log information to the network.
  • logging.handlers.SysLogHandler log output to syslog
  • logging.handlers.NTEventLogHandler remotely output logs to the event log of Windows NT/2000/XP 
  • logging.handlers.SMTPHandler remotely output logs to the email address
  • logging.handlers.MemoryHandler log output to the specified buffer in the memory
  • logging.handlers.HTTPHandler remotely outputs to HTTP server via "GET" or "POST"

Note: The specific usage of each Handler can be found in the reference book:

https://docs.python.org/2/library/logging.handlers.html#module-logging.handlers

        args represents the parameters passed to the handler class initialization method specified by class. It must be in the form of a tuple, even if there is only one parameter value, it must be in the form of a tuple; specify the output path, such as the output file name Wait.

        level is the same as the level in logger

        The formatter is the formatter used by the processor. The name of the formatter must appear in the section formatters, and there must be a section definition of the formatter in the configuration file; if the formatter is not specified, the handler will use the message itself as Log messages are recorded without adding additional information such as time and logger name;

        7. formatter_***: Set the format of the log content

                        

Configuration file usage

    Create a log.py file in the same level directory and write the following code

import logging.config


CONF_LOG = "log.conf"

#load config file
logging.config.fileConfig(CONF_LOG)


# create logger
# logger:file,fileAndConsole,rotatingFile
logger = logging.getLogger("fileAndConsole")




# "application" code
logger.debug("debug message")
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("critical message")

 

Guess you like

Origin blog.csdn.net/hhd1988/article/details/108650152