Python App ouput to syslog server

北慕城南 提交于 2021-02-07 06:56:48

问题


I'm trying to do some searching on google (looped for every 5 min or so). When it gets a hit I want it to push the results to a syslog server. I'm very new to python so please forgive the ignorance, I have searched for ages and can't find an answer to my question.

I intend to add multiple queries looking for diffirent results depending on the query results the logevent differs.

WARN "possible hit"
CRITICAL "definatly a hit"
etc

I would like the output to be for example like: log type, url, date/time

Below is the code I've been playing with so far. I can search and log to a file but not how I would like to. I'm only getting the formatting for time and the even type, I'm not getting my query results in the log. And i have no idea how to log to a syslog server.

#!/usr/bin/python
import urllib
import simplejson, logging

query = urllib.urlencode({'q' : 'SEARCHTERMHERE'})
url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' \ % (query)
search_results = urllib.urlopen(url)
json = simplejson.loads(search_results.read())
results = json['responseData']['results']
for i in results:
  logging.basicConfig(format='%(asctime)s %(message)s', filename='hits.log')
  logging.warning ('Likley hit')
  print i['url']

#!/usr/bin/python
import urllib
import simplejson 
import logging
from logging.handlers import SysLogHandler

query = urllib.urlencode({'q' : 'SEARCHTERMHERE'})
url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' \
% (query)

search_results = urllib.urlopen(url)
json = simplejson.loads(search_results.read())
results = json['responseData']['results']

for i in results:
  print i['url']
  logger = logging.getLogger()
  logger.addHandler(SysLogHandler(address=('192.168.0.2', 514), facility=LOG_USER, socktype=socket.SOCK_DGRAM)
  logger.addHandler(logging.FileHandler("hits.log"))
  logging.warn("likley Hit: " + i['url'])

I get : File "gog.py", line 18 logger.addHandler(logging.FileHandler("hits.log")) ^ SyntaxError: invalid syntax


回答1:


You can configure the logging module to output to syslog, see http://docs.python.org/library/logging.handlers.html#sysloghandler

Simple example:

from logging.handlers import SysLogHandler
import logging

logger = logging.getLogger()
logger.addHandler(SysLogHandler('/dev/log'))
logger.addHandler(logging.FileHandler("filename.log"))

logging.warn("Hello world")

The above logs to the local syslog using a Unix domain socket. You can also specify a hostname to log to syslog using UDP. See the docs for more info.



来源:https://stackoverflow.com/questions/8971074/python-app-ouput-to-syslog-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!