简体   繁体   English

从python程序写一个日志文件

[英]writing a log file from python program

I want to output some strings to a log file and I want the log file to be continuously updated. 我想将一些字符串输出到日志文件,我希望不断更新日志文件。

I have looked into the logging module pf python and found out that it is mostly about formatting and concurrent access. 我查看了python的日志记录模块 ,发现它主要是关于格式化和并发访问。

Please let me know if I am missing something or amy other way of doing it 如果我遗漏了某些东西或其他方式,请告诉我

usually i do the following: 通常我会做以下事情:

  # logging  
  LOG = "/tmp/ccd.log"                                                     
  logging.basicConfig(filename=LOG, filemode="w", level=logging.DEBUG)  

  # console handler  
  console = logging.StreamHandler()  
  console.setLevel(logging.ERROR)  
  logging.getLogger("").addHandler(console)

The logging part initialises logging's basic configurations . 日志记录部分初始化日志记录的基本配置 In the following I set up a console handler that prints out some logging information separately. 在下面我设置了一个控制台处理程序,它分别打印出一些日志信息。 Usually my console output is set to output only errors (logging.ERROR) and the detailed output in the LOG file. 通常我的控制台输出设置为仅输出错误(logging.ERROR)和LOG文件中的详细输出。

Your loggings will now printed to file. 您的记录现在将打印到文件。 For instance using: 例如使用:

logger = logging.getLogger(__name__)
logger.debug("hiho debug message")

or even 甚至

logging.debug("next line")

should work. 应该管用。

Doug Hellmann has a nice guide . Doug Hellmann有一个很好的指南

To add my 10cents with regards to using logging. 添加关于使用日志记录的10cents。 I've only recently discovered the Logging module and was put off at first. 我最近才发现了Logging模块,并且最初被推迟了。 Maybe just because it initially looks like a lot of work, but it's really simple and incredibly handy. 也许只是因为它最初看起来像很多工作,但它非常简单,非常方便。

This is the set up that I use. 这是我使用的设置。 Similar to Mkinds answer, but includes a timestamp. 类似于Mkinds的答案,但包括一个时间戳。

# Set up logging
log = "bot.log"
logging.basicConfig(filename=log,level=logging.DEBUG,format='%(asctime)s %(message)s', datefmt='%d/%m/%Y %H:%M:%S')
logging.info('Log Entry Here.')

Which will produce something like: 这会产生类似的东西:

22/09/2015 14:39:34 Log Entry Here.

You can log to a file with the Logging API. 您可以使用Logging API登录文件。

Example: http://docs.python.org/2/howto/logging.html#logging-to-a-file 示例: http//docs.python.org/2/howto/logging.html#logging-to-a-file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM