python Write Log File Operation Class and Application Example

  • 2021-07-06 11:28:09
  • OfStack

This paper describes the operation class and application of python writing log files. Share it for your reference, as follows:

During the development of the project, log files are indispensable. By writing log files, you can know the running situation of the program. Especially when deployed in a production environment, debug is generally not available at this time, and remote debug (remote debug) is available in some cases. That situation is another matter. Or use the usual log writing method, for example, in java, you can often see log4j, sf4j, logback and other three components to write logs.

How to implement in python, in fact, python itself also has a log operation library. It can be used directly. Here I used in the project to sort out 1 below, to share in the following, the implementation of the method, there are two main points

1. Classes that write logs

2. Log configuration files (handler, logger, and log save path, etc.)

Class that writes logs


'''
Created on 2012-2-17
@author: yihaomen.com
'''
import logging.config
import os
class INetLogger:
  log_instance = None
  @staticmethod
  def InitLogConf():
    currentDir=os.path.dirname(__file__)
    INetLogger.log_instance = logging.config.fileConfig(currentDir+os.path.sep+"logger.ini")
  @staticmethod
  def GetLogger(name = ""):
    if INetLogger.log_instance == None:
      INetLogger.InitLogConf()
    INetLogger.log_instance = logging.getLogger(name)
    return INetLogger.log_instance
if __name__ == "__main__":
  logger = INetLogger.GetLogger()
  logger.debug("debug message")
  logger.info("info message")
  logger.warn("warn message")
  logger.error("error message")
  logger.critical("critical message")
  logHello = INetLogger.GetLogger("root")
  logHello.info("Hello world!")

Log configuration file, in the same folder as the above class logger. ini


[loggers]
keys=root,mysql,socket
[handlers]
keys=consoleHandler,rotateFileHandler
[formatters]
keys=simpleFormatter
[formatter_simpleFormatter]
format=[%(asctime)s][%(levelname)s] [%(filename)s:%(lineno)d] [thread:%(thread)d]: %(message)s
[logger_root]
qualname=root
level=DEBUG
handlers=consoleHandler,rotateFileHandler
[logger_mysql]
qualname=mysql
level=DEBUG
handlers=rotateFileHandler
[logger_socket]
qualname=socket
level=ERROR
handlers=rotateFileHandler
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)
[handler_rotateFileHandler]
class=handlers.RotatingFileHandler
level=DEBUG
formatter=simpleFormatter
args=('c:/logs/InetServer.log', 'a', 2000000, 9)

If you use handler_rotateFileHandler, the log will be saved to the only c:/logs/InetServer. log file, and when the log exceeds 2000000 d, another file will be generated to save the record for 9 days, and you can configure it to 30, thus saving the log record for the last month.

For more readers interested in Python related contents, please check the topics of this site: "Summary of Python Log Operation Skills", "Summary of Python Function Use Skills", "Summary of Python String Operation Skills", "Introduction and Advanced Classic Tutorial of Python" and "Summary of Python File and Directory Operation Skills"

I hope this article is helpful to everyone's Python programming.


Related articles: