使用日志python类写入文件?

我如何使用Python中的日志logging类写入文件? 每次我尝试使用它,它只是打印出来的消息。

使用logging.basicConfig而不是logging.fileHandler()一个例子

 logging.basicConfig(filename=logname, filemode='a', format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s', datefmt='%H:%M:%S', level=logging.DEBUG) logging.info("Running Urban Planning") self.logger = logging.getLogger('urbanGUI') 

为了使这五个部分做到以下几点:

  1. 设置输出文件( filename=logname
  2. 将其设置为追加而不是覆盖( filemode='a'
  3. 确定输出消息的format=...format=...
  4. 确定输出时间的格式( datefmt='%H:%M:%S'
  5. 并确定它将接受的最低消息级别( level=logging.DEBUG )。

采自“ 日志食谱 ”:

 # create logger with 'spam_application' logger = logging.getLogger('spam_application') # create file handler which logs even debug messages fh = logging.FileHandler('spam.log') fh.setLevel(logging.DEBUG) logger.addHandler(fh) 

你很好走。

PS请确保阅读日志loggingHOWTO 。

http://docs.python.org/library/logging.html#logging.basicConfig

 logging.basicConfig(filename='/path/to/your/log', level=....) 

我更喜欢使用configuration文件。 它允许我切换日志级别,位置等,而无需在开发到发布时更改代码。 我只是简单地打包一个具有相同名称的不同configuration文件,并使用相同的logging器。

 import logging.config if __name__ == '__main__': # Configure the logger # loggerConfigFileName: The name and path of your configuration file logging.config.fileConfig(path.normpath(loggerConfigFileName)) # Create the logger # Admin_Client: The name of a logger defined in the config file mylogger = logging.getLogger('Admin_Client') msg='Bite Me' myLogger.debug(msg) myLogger.info(msg) myLogger.warn(msg) myLogger.error(msg) myLogger.critical(msg) # Shut down the logger logging.shutdown() 

这是我的日志configuration文件的代码

 #These are the loggers that are available from the code #Each logger requires a handler, but can have more than one [loggers] keys=root,Admin_Client #Each handler requires a single formatter [handlers] keys=fileHandler, consoleHandler [formatters] keys=logFormatter, consoleFormatter [logger_root] level=DEBUG handlers=fileHandler [logger_Admin_Client] level=DEBUG handlers=fileHandler, consoleHandler qualname=Admin_Client #propagate=0 Does not pass messages to ancestor loggers(root) propagate=0 # Do not use a console logger when running scripts from a bat file without a console # because it hangs! [handler_consoleHandler] class=StreamHandler level=DEBUG formatter=consoleFormatter args=(sys.stdout,)# The comma is correct, because the parser is looking for args [handler_fileHandler] class=FileHandler level=DEBUG formatter=logFormatter # This causes a new file to be created for each script # Change time.strftime("%Y%m%d%H%M%S") to time.strftime("%Y%m%d") # And only one log per day will be created. All messages will be amended to it. args=("D:\\Logs\\PyLogs\\" + time.strftime("%Y%m%d%H%M%S")+'.log', 'a') [formatter_logFormatter] #name is the name of the logger root or Admin_Client #levelname is the log message level debug, warn, ect #lineno is the line number from where the call to log is made #04d is simple formatting to ensure there are four numeric places with leading zeros #4s would work as well, but would simply pad the string with leading spaces, right justify #-4s would work as well, but would simply pad the string with trailing spaces, left justify #filename is the file name from where the call to log is made #funcName is the method name from where the call to log is made #format=%(asctime)s | %(lineno)d | %(message)s #format=%(asctime)s | %(name)s | %(levelname)s | %(message)s #format=%(asctime)s | %(name)s | %(module)s-%(lineno) | %(levelname)s | %(message)s #format=%(asctime)s | %(name)s | %(module)s-%(lineno)04d | %(levelname)s | %(message)s #format=%(asctime)s | %(name)s | %(module)s-%(lineno)4s | %(levelname)-8s | %(message)s format=%(asctime)s | %(levelname)-8s | %(lineno)04d | %(message)s #Use a separate formatter for the console if you want [formatter_consoleFormatter] format=%(asctime)s | %(levelname)-8s | %(filename)s-%(funcName)s-%(lineno)04d | %(message)s 

http://docs.python.org/library/logging.handlers.html#filehandler

位于核心logging包中的FileHandler类将日志logging输出发送到磁盘文件。

 import sys import logging from util import reducer_logfile logging.basicConfig(filename=reducer_logfile, format='%(message)s', level=logging.INFO, filemode='w')