Nic*_*ack 11 python logging syslog
当我在我的mac上运行时:
import logging.handlers
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
syslog_address = '/var/run/syslog'
logger.addHandler(logging.handlers.SysLogHandler(syslog_address))
logger.error("What the crap?")
Run Code Online (Sandbox Code Playgroud)
它在syslog中显示如下:
Oct 18 19:02:06 nick Unknown[4294967295] <Error>: What the crap?
Run Code Online (Sandbox Code Playgroud)
为什么它是未知的?在剧本名称之后,它不应该足够聪明吗?
Vin*_*jip 15
我认为APP-NAME(表示源)是syslog头中的可选组件.最新版本的SysLogHandler(适用于Python 3.3)包括对APP-NAME的支持(ident根据C syslog API调用),但在早期版本中不可用.看到这个Python问题.
如果您将脚本名称添加到所有消息之前,您将获得所需的效果.例如,
logger.error('foo: What\'s up?')
Run Code Online (Sandbox Code Playgroud)
将显示例如
19/10/2011 13:51:17 foo [2147483647]怎么了?
在日志中.
为了得到你需要的东西,你应该在处理程序中添加一个格式化程序,这样你就不必自己手动格式化每条消息.
import logging.handlers
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
syslog_address = '/var/run/syslog'
handler = logging.handlers.SysLogHandler(syslog_address)
# create the formatter
formatter = logging.Formatter('%(name)s: [%(levelname)s] %(message)s')
# plug this formatter into your handler(s)
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.error("What the crap?")
Run Code Online (Sandbox Code Playgroud)
您现在应该发现您在syslog中看到了您期望的条目:
Jul 4 14:34:40 ip-127-0-0-1 script_name.py: [ERROR] What the crap?
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4275 次 |
| 最近记录: |