使用日志python类写入文件?

Tak*_*kun 96 python logging

如何在python中使用日志记录类来写入文件?每次我尝试使用它时,它只会打印出消息.

the*_*ner 139

使用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')
Run Code Online (Sandbox Code Playgroud)

按顺序,这五个部分执行以下操作:

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

  • 他最后一行的目的是什么?即 `logger =logging.getLogger('urbanGUI')` (12认同)
  • @Vichoko,它与这个答案无关,它只是如何使用记录器的示例。请参阅[文档](https://docs.python.org/3/library/logging.html#logging.getLogger)以了解它的作用。 (5认同)
  • 确保这不在 `if __name__ == '__main__':` 下,如果在 apache 上运行 (4认同)
  • 我想指出的是,默认情况下,此记录器不是线程安全的,它不会记录未捕获的异常,asctime 不能同时具有时区和毫秒,并且它不会同时记录文件并同时打印到控制台。处理这些情况的一个选项是 [lovely-logger](https://pypi.org/project/lovely-logger/) 模块——尽管它们都可以仅使用标准库来克服。 (4认同)
  • @RamiAlloush 你能详细说明一下吗?这是为什么?(好奇心:)) (3认同)
  • @notihs,服务器不会直接运行脚本文件,因此下面的部分 `if __name__ == '__main__':` 不会被执行。 (2认同)

Eli*_*sky 56

取自" 伐木食谱 ":

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

你很高兴去.

PS确保也阅读日志记录HOWTO.

  • 要回答您的第一个问题,请随时查看我问的问题的标题.我已经查看了您提供的链接,这很有帮助.我已经复制了你给我的代码,我错误地认为我能够成功使用logger.info("message")和logger.warning("message")?我能够使用logger.warning写入该文件,但是logger.info似乎没有写入该文件. (4认同)
  • 如果你想写info/debug msgs,那么编写的代码示例@EliBendersky缺少一步.记录器本身需要将自己的日志级别配置为接受该级别的日志记录消息,例如`logger.setLevel(logging.DEBUG)`.记录器可以配置多个处理程序; 记录器中配置的级别确定要将哪些严重性级别日志消息发送到其每个处理程序,并且处理程序中设置的级别确定处理程序将处理哪些级别.请注意,那些想要打印信息消息的人只需要在记录器和处理程序中将其设置为"INFO". (3认同)
  • 我无法让这个为logger.info工作. (2认同)
  • 我只能使用`logger.warning("message")`来写出文件,不能使用`logger.info("message")`或``logger.debug("message")`.这有点烦人. (2认同)
  • 我已经更新了示例以执行“logger.setLevel(logging.DEBUG)”——感谢您的评论 (2认同)

Bil*_*idd 12

我更喜欢使用配置文件.当我从开发到发布时,它允许我在不更改代码的情况下切换日志记录级别,位置等.我只是打包一个具有相同名称的不同配置文件,并使用相同的定义记录器.

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()
Run Code Online (Sandbox Code Playgroud)

这是我的日志配置文件的代码

#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
Run Code Online (Sandbox Code Playgroud)

  • 用日期命名文件需要在Python 3中使用双`%%`。例如`time.strftime("%%Y%%m%%D")` (2认同)

Alo*_*rad 11

这是两个示例,一个打印日志 (stdout),另一个将日志写入文件:

import logging
import sys

logger = logging.getLogger()
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s | %(levelname)s | %(message)s')

stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setLevel(logging.DEBUG)
stdout_handler.setFormatter(formatter)

file_handler = logging.FileHandler('logs.log')
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)


logger.addHandler(file_handler)
logger.addHandler(stdout_handler)
Run Code Online (Sandbox Code Playgroud)

在此示例中,所有日志都将被打印并写入名为 logs.log 的文件中

使用示例:

logger.info('This is a log message!')
logger.error('This is an error message.')
Run Code Online (Sandbox Code Playgroud)

所有内置日志处理程序的列表https://docs.python.org/3/library/logging.handlers.html


Gry*_*ius 10

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

logging.basicConfig(filename='/path/to/your/log', level=....)
Run Code Online (Sandbox Code Playgroud)

  • 这将日志保存在文件中,这很好。如果与此一起,我希望它也将输出记录在终端上怎么办? (2认同)

pdp*_*pdp 8

这是一个更简单的方法。此解决方案不使用配置字典并使用旋转文件处理程序,如下所示:

import logging
from logging.handlers import RotatingFileHandler
     
logging.basicConfig(handlers=[RotatingFileHandler(filename=logpath+filename,
                     mode='w', maxBytes=512000, backupCount=4)], level=debug_level,
                     format='%(levelname)s %(asctime)s %(message)s', 
                    datefmt='%m/%d/%Y%I:%M:%S %p')
     
logger = logging.getLogger('my_logger')
Run Code Online (Sandbox Code Playgroud)

或者像这样:

import logging
from logging.handlers import RotatingFileHandler
     
handlers = [ RotatingFileHandler(filename=logpath+filename, 
            mode='w', 
            maxBytes=512000, 
            backupCount=4)
           ]
logging.basicConfig(handlers=handlers, 
                    level=debug_level, 
                    format='%(levelname)s %(asctime)s %(message)s', 
                    datefmt='%m/%d/%Y%I:%M:%S %p')
     
logger = logging.getLogger('my_logger')
Run Code Online (Sandbox Code Playgroud)

handlers 变量需要是可迭代的。logpath+filename 和 debug_level 只是保存各自信息的变量。当然,函数 params 的值由您决定。

我第一次使用日志记录模块时,我写了以下错误,这会产生 OS 文件锁定错误(以上是解决方案):

import logging
from logging.handlers import RotatingFileHandler
     
logging.basicConfig(filename=logpath+filename, 
       level=debug_level, 
       format='%(levelname)s %(asctime)s %(message)s', 
       datefmt='%m/%d/%Y%I:%M:%S %p')
     
logger = logging.getLogger('my_logger')
logger.addHandler(RotatingFileHandler(
       filename=logpath+filename, 
       mode='w', 
       maxBytes=512000, 
       backupCount=4))
Run Code Online (Sandbox Code Playgroud)


JAB*_*JAB 6

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

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

  • +1 有关完整示例,请参阅“基本教程”:http://docs.python.org/howto/logging.html#logging-to-a-file (4认同)

mut*_*mar 6

这个例子应该可以正常工作。我已经为控制台添加了流处理程序。控制台日志和文件处理程序数据应该类似。

    # MUTHUKUMAR_TIME_DATE.py #>>>>>>>> file name(module)

    import sys
    import logging
    import logging.config
    # ================== Logger ================================
    def Logger(file_name):
        formatter = logging.Formatter(fmt='%(asctime)s %(module)s,line: %(lineno)d %(levelname)8s | %(message)s',
                                      datefmt='%Y/%m/%d %H:%M:%S') # %I:%M:%S %p AM|PM format
        logging.basicConfig(filename = '%s.log' %(file_name),format= '%(asctime)s %(module)s,line: %(lineno)d %(levelname)8s | %(message)s',
                                      datefmt='%Y/%m/%d %H:%M:%S', filemode = 'w', level = logging.INFO)
        log_obj = logging.getLogger()
        log_obj.setLevel(logging.DEBUG)
        # log_obj = logging.getLogger().addHandler(logging.StreamHandler())

        # console printer
        screen_handler = logging.StreamHandler(stream=sys.stdout) #stream=sys.stdout is similar to normal print
        screen_handler.setFormatter(formatter)
        logging.getLogger().addHandler(screen_handler)

        log_obj.info("Logger object created successfully..")
        return log_obj
    # =======================================================


MUTHUKUMAR_LOGGING_CHECK.py #>>>>>>>>>>> file name
# calling **Logger** function
file_name = 'muthu'
log_obj =Logger(file_name)
log_obj.info("yes   hfghghg ghgfh".format())
log_obj.critical("CRIC".format())
log_obj.error("ERR".format())
log_obj.warning("WARN".format())
log_obj.debug("debug".format())
log_obj.info("qwerty".format())
log_obj.info("asdfghjkl".format())
log_obj.info("zxcvbnm".format())
# closing file
log_obj.handlers.clear()

OUTPUT:
2019/07/13 23:54:40 MUTHUKUMAR_TIME_DATE,line: 17     INFO | Logger object created successfully..
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 8     INFO | yes   hfghghg ghgfh
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 9 CRITICAL | CRIC
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 10    ERROR | ERR
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 11  WARNING | WARN
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 12    DEBUG | debug
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 13     INFO | qwerty
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 14     INFO | asdfghjkl
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 15     INFO | zxcvbnm

Thanks, 
Run Code Online (Sandbox Code Playgroud)