Python application for output to syslog server

I am trying to do a google search (looping every 5 minutes or so). When it gets hit, I want it to output the results to the syslog server. I am very new to python, so please forgive ignorance, I searched forever and cannot find the answer to my question.

I intend to add some queries looking for diffirent results, depending on the query results, which are different from logevent.

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

I would like the result to be, for example, the following: log type, URL, date / time

Below is the code I played with so far. I can search and register in a file, but not in the way I would like. I only get formatting for time and even type, I do not get query results in the log. And I have no idea how to connect to the 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")) ^ Syntax Error: invalid syntax

+4
source share
1 answer

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

A 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 are written to the local syslog using a Unix domain socket. You can also specify the host name to log in to syslog using UDP. See the docs for more details.

+6
source

Source: https://habr.com/ru/post/1392457/


All Articles