如何在 Python 中配置日志记录到 syslog?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3968669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to configure logging to syslog in Python?
提问by thor
I can't get my head around Python's loggingmodule. My needs are very simple: I just want to log everything to syslog. After reading documentation I came up with this simple test script:
我无法理解 Python 的logging模块。我的需求非常简单:我只想将所有内容都记录到系统日志中。阅读文档后,我想出了这个简单的测试脚本:
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')
But this script does not produce any log records in syslog. What's wrong?
但是这个脚本不会在 syslog 中产生任何日志记录。怎么了?
采纳答案by dr jimbob
Change the line to this:
将行更改为:
handler = SysLogHandler(address='/dev/log')
This works for me
这对我有用
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')
回答by bstpierre
Is your syslog.conf set up to handle facility=user?
您的 syslog.conf 是否设置为处理工具=用户?
You can set the facility used by the python logger with the facility argument, something like this:
您可以使用工具参数设置 python 记录器使用的工具,如下所示:
handler = logging.handlers.SysLogHandler(facility=SysLogHandler.LOG_DAEMON)
回答by Oliver Henriot
I add a little extra comment just in case it helps anyone because I found this exchange useful but needed this little extra bit of info to get it all working.
我添加了一些额外的评论,以防万一它对任何人有所帮助,因为我发现这种交流很有用,但需要这些额外的信息才能使其全部正常工作。
To log to a specific facility using SysLogHandler you need to specify the facility value. Say for example that you have defined:
要使用 SysLogHandler 登录到特定设施,您需要指定设施值。比如说你已经定义了:
local3.* /var/log/mylog
local3.* /var/log/mylog
in syslog, then you'll want to use:
在 syslog 中,那么您将需要使用:
handler = logging.handlers.SysLogHandler(address = ('localhost',514), facility=19)
handler = logging.handlers.SysLogHandler(address = ('localhost',514), facility=19)
and you also need to have syslog listening on UDP to use localhost instead of /dev/log.
并且您还需要让 syslog 监听 UDP 以使用 localhost 而不是 /dev/log。
回答by San
import syslog
syslog.openlog(ident="LOG_IDENTIFIER",logoption=syslog.LOG_PID, facility=syslog.LOG_LOCAL0)
syslog.syslog('Log processing initiated...')
the above script will log to LOCAL0 facility with our custom "LOG_IDENTIFIER"... you can use LOCAL[0-7] for local purpose.
上面的脚本将使用我们的自定义“LOG_IDENTIFIER”登录到 LOCAL0 设施……您可以将 LOCAL[0-7] 用于本地目的。
回答by egrep
You should alwaysuse the local host for logging, whether to /dev/log or localhost through the TCP stack. This allows the fully RFC compliant and featureful system logging daemon to handle syslog. This eliminates the need for the remote daemon to be functional and provides the enhanced capabilities of syslog daemon's such as rsyslog and syslog-ng for instance. The same philosophy goes for SMTP. Just hand it to the local SMTP software. In this case use 'program mode' not the daemon, but it's the same idea. Let the more capable software handle it. Retrying, queuing, local spooling, using TCP instead of UDP for syslog and so forth become possible. You can also [re-]configure those daemons separately from your code as it should be.
您应该始终使用本地主机进行日志记录,无论是通过 TCP 堆栈记录到 /dev/log 还是 localhost。这允许完全符合 RFC 且功能强大的系统日志守护进程来处理 syslog。这消除了远程守护程序运行的需要,并提供了 syslog 守护程序(例如 rsyslog 和 syslog-ng)的增强功能。SMTP 也有同样的理念。只需将其交给本地 SMTP 软件即可。在这种情况下,使用“程序模式”而不是守护程序,但这是相同的想法。让功能更强大的软件来处理它。重试、排队、本地假脱机、对系统日志使用 TCP 而不是 UDP 等成为可能。您还可以[重新]配置那些与您的代码分开的守护程序,因为它应该是。
Save your coding for your application, let other software do it's job in concert.
保存您的应用程序编码,让其他软件协同工作。
回答by luismartingil
From https://github.com/luismartingil/per.scripts/tree/master/python_syslog
来自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')
回答by boatcoder
Piecing things together from here and other places, this is what I came up with that works on unbuntu 12.04 and centOS6
将这里和其他地方的东西拼凑起来,这就是我想出的适用于 unbuntu 12.04 和 centOS6 的方法
Create an file in /etc/rsyslog.d/that ends in .conf and add the following text
创建一个/etc/rsyslog.d/以 .conf 结尾的文件并添加以下文本
local6.* /var/log/my-logfile
Restart rsyslog, reloading did NOT seem to work for the new log files. Maybe it only reloads existing conf files?
重新启动rsyslog,重新加载似乎不适用于新的日志文件。也许它只重新加载现有的 conf 文件?
sudo restart rsyslog
Then you can use this test program to make sure it actually works.
然后你可以使用这个测试程序来确保它确实有效。
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")
回答by Reshad user2701173
You can also add a file handler or rotating file handler to send your logs to a local file: http://docs.python.org/2/library/logging.handlers.html
您还可以添加文件处理程序或旋转文件处理程序以将您的日志发送到本地文件:http: //docs.python.org/2/library/logging.handlers.html
回答by lindes-hw
I found the syslog moduleto make it quite easy to get the basic logging behavior you describe:
我发现syslog 模块可以很容易地获得您描述的基本日志记录行为:
import syslog
syslog.syslog("This is a test message")
syslog.syslog(syslog.LOG_INFO, "Test message at INFO priority")
There are other things you could do, too, but even just the first two lines of that will get you what you've asked for as I understand it.
你也可以做其他的事情,但即使只是前两行,你也会得到你所要求的,正如我所理解的。
回答by Bruce Edge
Here's the yaml dictConfig way recommended for 3.2 & later.
这是 3.2 及更高版本推荐的 yaml dictConfig 方式。
In log cfg.yml:
在日志中cfg.yml:
version: 1
disable_existing_loggers: true
formatters:
default:
format: "[%(process)d] %(name)s(%(funcName)s:%(lineno)s) - %(levelname)s: %(message)s"
handlers:
syslog:
class: logging.handlers.SysLogHandler
level: DEBUG
formatter: default
address: /dev/log
facility: local0
rotating_file:
class: logging.handlers.RotatingFileHandler
level: DEBUG
formatter: default
filename: rotating.log
maxBytes: 10485760 # 10MB
backupCount: 20
encoding: utf8
root:
level: DEBUG
handlers: [syslog, rotating_file]
propogate: yes
loggers:
main:
level: DEBUG
handlers: [syslog, rotating_file]
propogate: yes
Load the config using:
使用以下命令加载配置:
log_config = yaml.safe_load(open('cfg.yml'))
logging.config.dictConfig(log_config)
Configured both syslog & a direct file. Note that the /dev/logis OS specific.
配置了系统日志和直接文件。请注意,这/dev/log是特定于操作系统的。

