Python:使用时间戳

时间:2017-05-16 00:54:27

标签: python logging error-logging

我正在编写一个通过SSH连接到N个主机的脚本...查询第三方系统并提取数据,然后以特定格式显示所有收集的数据。

我想记录脚本执行的所有操作以及在控制台和日志文件上遇到的任何异常,以便用户可以看到脚本运行时发生的情况(如果有人使用Ansible - 然后就像我们在控制台上获得的输出和运行剧本时的日志一样)

预期输出

  • [时间戳]:连接机器1
  • [timestamp]:建立连接
  • [timestamp]:查询数据库xyz
  • [timestamp]:错误:凭据无效
  • [timestamp]:中止数据提取
  • [时间戳]:连接已关闭
  • [timestamp]:---------------------------
  • [时间戳]:连接机器2
  • [timestamp]:建立连接
  • [timestamp]:查询数据库xyz
  • [时间戳]:提取完成
  • [timestamp]:关闭连接

我希望我能够正确解释它 - 使用时间戳记录整个脚本和所有数据迭代的操作和异常。

请使用该技术的示例脚本提供建议,如果可能的话。感谢

2 个答案:

答案 0 :(得分:2)

You can have a look here for some more detailed guidance. Here's how I usually set up logging on my stuff:

import logging

...

logger = logging.getLogger()
log_handler = logging.StreamHandler(sys.stdout)
log_handler.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s - %(funcName)s - line %(lineno)d"))
log_handler.setLevel(logging.DEBUG)
logger.addHandler(log_handler)
logger.setLevel(logging.DEBUG)

This will produce output like this, for any event from DEBUG upwards:

2017-05-16 13:30:03,193 - root - INFO - Starting execution - main - line 35
2017-05-16 13:30:03,206 - root - DEBUG - Config file grabbed successfully - readConfig - line 71
...
2017-05-15 13:30:26,792 - root - WARNING - Reached maximum number of attempts (3) for this request; skipping request. - main - line 79
2017-05-15 13:30:26,797 - root - ERROR - Failed to grab item. Unfortunately, this is a showstopper :( - main - line 79

The above is produced by a line in the main function of my app, that reads:

logger.info("Starting execution")

Another line in my readConfig function:

logging.debug("Config file grabbed successfully")

And another two lines in main again:

logging.warning("Reached maximum number of attempts ({max_attempts}) for this request; skipping request.".format(max_attempts = max_tries))
...
logging.error("Failed to grab item. Unfortunately, this is a showstopper :(")

Then it's a matter of how much information and context you need on each log entry. Have a look here at formatting the entries, and here at formatters. I'll have these sent to me via email, anytime the app runs triggered by crontab, by adding MAILTO = root to the top of my crontab file, and making sure my system email is properly set.

If you want to set it to go to the console and a file, you'll just need to set two different handlers. This answer provides a good example, where you'd set a StreamHandler to log to the console, and a FileHandler to log to a file. So instead of setting it up as I mentioned above I usually do, you could try:

import logging

...

# Set up logging and formatting
logger = logging.getLogger()
logFormatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s - %(funcName)s - line %(lineno)d")

# Set up the console handler
consoleHandler = logging.StreamHandler()
consoleHandler.setFormatter(logFormatter)
logger.addHandler(consoleHandler)

# Set up the file handler 
fileHandler = logging.FileHandler("{0}/{1}.log".format(logPath, fileName))
fileHandler.setFormatter(logFormatter)
logger.addHandler(fileHandler)

# Set up logging levels
consoleHandler.setLevel(logging.DEBUG)
fileHandler.setLevel(logging.DEBUG)
logger.setLevel(logging.DEBUG)

答案 1 :(得分:1)

查看日志记录模块here,这是一个包含基本和高级应用程序的不错示例部分。以您所描述的格式进行操作似乎包含在教程中。

相关问题