我无法理解Python的logging
模块.我的需求非常简单:我只想将所有内容记录到syslog中.阅读文档后,我想出了这个简单的测试脚本:
import logging import logging.handlers my_logger = logging.getLogger('MyLogger') my_logger.setLevel(logging.DEBUG) handler = logging.handlers.SysLogHandler() my_logger.addHandler(handler) my_logger.debug('this is debug') my_logger.critical('this is critical')
但是此脚本不会在syslog中生成任何日志记录.怎么了?
将行更改为:
handler = SysLogHandler(address='/dev/log')
这适合我
import logging import logging.handlers my_logger = logging.getLogger('MyLogger') my_logger.setLevel(logging.DEBUG) handler = logging.handlers.SysLogHandler(address = '/dev/log') my_logger.addHandler(handler) my_logger.debug('this is debug') my_logger.critical('this is critical')
您应始终使用本地主机进行日志记录,无论是通过TCP堆栈还是/ dev/log或localhost.这允许完全符合RFC且功能强大的系统日志记录守护程序来处理syslog.这消除了远程守护进程功能的需要,并提供了syslog守护进程的增强功能,例如rsyslog和syslog-ng.SMTP也是如此.只需将其交给本地SMTP软件即可.在这种情况下使用'程序模式'而不是守护进程,但它是相同的想法.让功能更强大的软件处理它.可以重试,排队,本地假脱机,使用TCP而不是UDP来进行系统日志等.您也可以[代码]单独[重新]配置这些守护程序.
保存您的应用程序编码,让其他软件协同工作.
我发现syslog模块可以很容易地获得您描述的基本日志记录行为:
import syslog syslog.syslog("This is a test message") syslog.syslog(syslog.LOG_INFO, "Test message at INFO priority")
还有其他一些你可以做的事情,但即便只是前两行也会让你得到我所理解的东西.
从这里和其他地方拼凑起来的东西,这就是我提出的可以在unbuntu 12.04和centOS6上运行的东西
/etc/rsyslog.d/
在.conf中创建一个文件并添加以下文本
local6.* /var/log/my-logfile
重新启动rsyslog
,重新加载似乎不适用于新的日志文件.也许它只重新加载现有的conf文件?
sudo restart rsyslog
然后你可以使用这个测试程序来确保它确实有效.
import logging, sys from logging import config LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(module)s P%(process)d T%(thread)d %(message)s' }, }, 'handlers': { 'stdout': { 'class': 'logging.StreamHandler', 'stream': sys.stdout, 'formatter': 'verbose', }, 'sys-logger6': { 'class': 'logging.handlers.SysLogHandler', 'address': '/dev/log', 'facility': "local6", 'formatter': 'verbose', }, }, 'loggers': { 'my-logger': { 'handlers': ['sys-logger6','stdout'], 'level': logging.DEBUG, 'propagate': True, }, } } config.dictConfig(LOGGING) logger = logging.getLogger("my-logger") logger.debug("Debug") logger.info("Info") logger.warn("Warn") logger.error("Error") logger.critical("Critical")
我添加了一些额外的评论以防万一它可以帮助任何人,因为我发现这个交换有用,但需要这些额外的信息来使它全部工作.
要使用SysLogHandler登录到特定设施,您需要指定设施值.比如你已经定义了:
local3.* /var/log/mylog
在syslog中,那么你将要使用:
handler = logging.handlers.SysLogHandler(address = ('localhost',514), facility=19)
并且您还需要在UDP上侦听syslog以使用localhost而不是/ dev/log.
您的syslog.conf是否设置为处理facility = user?
您可以使用facility参数设置python logger使用的工具,如下所示:
handler = logging.handlers.SysLogHandler(facility=SysLogHandler.LOG_DAEMON)
import syslog syslog.openlog(ident="LOG_IDENTIFIER",logoption=syslog.LOG_PID, facility=syslog.LOG_LOCAL0) syslog.syslog('Log processing initiated...')
上面的脚本将使用我们的自定义"LOG_IDENTIFIER"登录LOCAL0工具......您可以将LOCAL [0-7]用于本地目的.
来自https://github.com/luismartingil/per.scripts/tree/master/python_syslog
#!/usr/bin/python # -*- coding: utf-8 -*- ''' Implements a new handler for the logging module which uses the pure syslog python module. @author: Luis Martin Gil @year: 2013 ''' import logging import syslog class SysLogLibHandler(logging.Handler): """A logging handler that emits messages to syslog.syslog.""" FACILITY = [syslog.LOG_LOCAL0, syslog.LOG_LOCAL1, syslog.LOG_LOCAL2, syslog.LOG_LOCAL3, syslog.LOG_LOCAL4, syslog.LOG_LOCAL5, syslog.LOG_LOCAL6, syslog.LOG_LOCAL7] def __init__(self, n): """ Pre. (0 <= n <= 7) """ try: syslog.openlog(logoption=syslog.LOG_PID, facility=self.FACILITY[n]) except Exception , err: try: syslog.openlog(syslog.LOG_PID, self.FACILITY[n]) except Exception, err: try: syslog.openlog('my_ident', syslog.LOG_PID, self.FACILITY[n]) except: raise # We got it logging.Handler.__init__(self) def emit(self, record): syslog.syslog(self.format(record)) if __name__ == '__main__': """ Lets play with the log class. """ # Some variables we need _id = 'myproj_v2.0' logStr = 'debug' logFacilityLocalN = 1 # Defines a logging level and logging format based on a given string key. LOG_ATTR = {'debug': (logging.DEBUG, _id + ' %(levelname)-9s %(name)-15s %(threadName)-14s +%(lineno)-4d %(message)s'), 'info': (logging.INFO, _id + ' %(levelname)-9s %(message)s'), 'warning': (logging.WARNING, _id + ' %(levelname)-9s %(message)s'), 'error': (logging.ERROR, _id + ' %(levelname)-9s %(message)s'), 'critical': (logging.CRITICAL, _id + ' %(levelname)-9s %(message)s')} loglevel, logformat = LOG_ATTR[logStr] # Configuring the logger logger = logging.getLogger() logger.setLevel(loglevel) # Clearing previous logs logger.handlers = [] # Setting formaters and adding handlers. formatter = logging.Formatter(logformat) handlers = [] handlers.append(SysLogLibHandler(logFacilityLocalN)) for h in handlers: h.setFormatter(formatter) logger.addHandler(h) # Yep! logging.debug('test debug') logging.info('test info') logging.warning('test warning') logging.error('test error') logging.critical('test critical')