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
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.