[英]How to send python logs to syslogs?
I am using logging for generating logs on my python (2.7) project. 我正在使用日志记录在python(2.7)项目上生成日志。 I create one instance of logger class on each python file (
LOGGER = logging.getLogger(__name__)
like this). 我在每个python文件上创建了一个logger类实例(
LOGGER = logging.getLogger(__name__)
这样)。
I want to send all the logs to syslog. 我想将所有日志发送到syslog。 Ways I have found using SysLogHandler needs to specify the address (
/dev/log
, /var/run/syslog
etc.) of syslogs which can be different on different platforms. 我发现使用SysLogHandler的方式需要指定
/var/run/syslog
的地址( /dev/log
, /var/run/syslog
等),该地址在不同平台上可能会有所不同。
Is there any generic way to do it (send the logs to syslog)? 有什么通用的方法(将日志发送到syslog)吗?
As you found, you configure logging to use the SysLogHandler. 如您所见,您将日志记录配置为使用SysLogHandler。 As you also noted, the "address" will be different on different systems and configurations.
您还注意到,在不同的系统和配置上,“地址”将有所不同。 You will need to make that a configurable part of your application.
您将需要使它成为您应用程序的可配置部分。
If you are configuring the logging programmatically, you could implement some heuristics to search for the various UNIX domain socket paths you expect to find. 如果您以编程方式配置日志记录,则可以实施一些启发式搜索,以搜索期望找到的各种UNIX域套接字路径。
Note the syslog can use UDP or TCP sockets to log to a remote syslog server instead of using a UNIX domain socket on the local machine. 请注意,系统日志可以使用UDP或TCP套接字登录到远程系统日志服务器,而不是在本地计算机上使用UNIX域套接字。
import sys, logging
class streamToLogger(object):
def __init__(self, logger, log_level = logging.INFO):
self.logger = logger
self.log_level = log_level
self.linebuf = ''
def write(self, buf):
for line in buf.rstrip().splitlines():
self.logger.log(self.log_level, line.rstrip())
logging.basicConfig(
level = logging.DEBUG,
format = '%(asctime)s:%(levelname)s:%(name)s:%(message)s',
filename = os.path.join('/var/log', 'logfile.log'),
filemode = 'a'
)
sys.stdout = streamToLogger(logging.getLogger('STDOUT'), logging.INFO)
sys.stderr = streamToLogger(logging.getLogger('STDERR'), logging.ERROR)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.