Python에서 syslog에 로깅을 구성하는 방법은 무엇입니까?
파이썬 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')
당신은해야한다 항상 로는 / dev / TCP 스택을 통해 로그인 또는 로컬 호스트 여부, 로깅을위한 로컬 호스트를 사용합니다. 이를 통해 RFC를 완벽하게 준수하고 기능적인 시스템 로깅 데몬이 syslog를 처리 할 수 있습니다. 따라서 원격 데몬이 작동하지 않아도되고 rsyslog 및 syslog-ng와 같은 syslog 데몬의 향상된 기능이 제공됩니다. SMTP에도 같은 철학이 적용됩니다. 로컬 SMTP 소프트웨어로 전달하십시오. 이 경우 데몬이 아닌 '프로그램 모드'를 사용하지만 같은 생각입니다. 더 유능한 소프트웨어가 처리하도록하십시오. syslog 등에 UDP 대신 TCP를 사용하여 재시도, 큐잉, 로컬 스풀링 등이 가능합니다. 코드와는 별도로 데몬을 [재설정] 구성 할 수도 있습니다.
응용 프로그램의 코딩을 저장하고 다른 소프트웨어가 함께 작동하게하십시오.
설명하는 기본 로깅 동작을 쉽게 얻을 수 있도록 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")
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:
local3.* /var/log/mylog
in syslog, then you'll want to use:
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.
Is your syslog.conf set up to handle facility=user?
You can set the facility used by the python logger with the facility argument, something like this:
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...')
the above script will log to LOCAL0 facility with our custom "LOG_IDENTIFIER"... you can use LOCAL[0-7] for local purpose.
From 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')
Here's the yaml dictConfig way recommended for 3.2 & later.
In log 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/log
is OS specific.
I fix it on my notebook. The rsyslog service did not listen on socket service.
I config this line bellow in /etc/rsyslog.conf
file and solved the problem:
$SystemLogSocketName /dev/log
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
참고URL : https://stackoverflow.com/questions/3968669/how-to-configure-logging-to-syslog-in-python
'program story' 카테고리의 다른 글
두 Django 앱간에 모델을 이동하는 방법 (Django 1.7) (0) | 2020.08.02 |
---|---|
HTML에서 페이지를 새로 고칠 때 페이지 스크롤 위치를 맨 위로 이동 (0) | 2020.08.02 |
투명한 이미지를 위해 가능한 가장 작은 데이터 URI 이미지 (0) | 2020.07.30 |
함수 내에서 전역 변수의 값을 변경하는 방법 (0) | 2020.07.30 |
실제 wsdl 파일만으로 서비스 참조를 생성하는 방법 (0) | 2020.07.30 |