Skip to content

Instantly share code, notes, and snippets.

@peterfroehlich
Forked from derlinkshaender/README.rst
Last active December 20, 2015 05:39
Show Gist options
  • Save peterfroehlich/6080519 to your computer and use it in GitHub Desktop.
Save peterfroehlich/6080519 to your computer and use it in GitHub Desktop.

graystreamlogger

Introduction

graystreamlogger is a python script born out of necessity. Use graylogger.py to send GELF-formatted messages to a graylog host. You may log string messages, file contents or read from stdin, add additional fields. Host name and timestamp will be provided automatically.

This is based on Armins graylogger.py and was ment to be used in apache. It opens stdin non blocking to accept a continues logging stream seperated by newlines. It is working but is a bit crud to be used in production...

Credits and Thank You

License

MIT License

Copyright (c) 2013 Armin Hanisch

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#!/usr/bin/python
import sys
import os
import logging
import argparse
import graypy
import fcntl
from time import sleep
def bailout(msg):
sys.stderr.write(msg + '\n')
exit(1)
def check_args():
loglevels = { 'DEBUG': logging.DEBUG,
'INFO': logging.INFO,
'WARNING': logging.WARNING,
'ERROR': logging.ERROR,
'CRITICAL': logging.CRITICAL }
cmdline_options = { "facility": "PythonLogger",
"version": "1.0",
"level": 1,
"server": None,
"data": None,
"port": 12201 }
parser = argparse.ArgumentParser(description='send a message to a graylog server',
usage='%(prog)s [options] SERVER MESSAGE')
parser.add_argument("server", help="graylog server name")
parser.add_argument("-l", "--level", help="log level (defaults to ALERT)", choices=loglevels)
parser.add_argument("-f", "--facility", help="facility name (defaults to 'PythonLogger')")
parser.add_argument("-p", "" "--port", help="graylog port (defaults to 12201)", type=int)
parser.add_argument("-d", "" "--data", help="additional data field (key:value)", action="append")
args = parser.parse_args()
cmdline_options['server'] = args.server
# check port override
if args.port is not None:
cmdline_options['port'] = args.port
# process facility option
if args.facility is not None:
cmdline_options['facility'] = args.facility
# set the level
if args.level is not None:
cmdline_options['level'] = loglevels[args.level.upper()]
# process additional data fields, if present
if args.data is not None:
cmdline_options['data'] = {}
for entry in args.data:
entry = entry.strip().split(':')
key = entry[0]
value = ''.join(entry[1:])
cmdline_options['data'][key] = value
return cmdline_options
def main():
try:
args = check_args()
my_logger = logging.getLogger(args['facility'])
my_logger.setLevel(args['level'])
handler = graypy.GELFHandler(args['server'], args['port'], debugging_fields=False)
my_logger.addHandler(handler)
d = args['data']
# make stdin a non-blocking file
fd = sys.stdin.fileno()
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
# user input handling thread
while 1:
try:
input = sys.stdin.readline()
# Exit on EOF
if len(input) == 0:
exit()
my_logger.log(args['level'], input, extra=d)
except KeyboardInterrupt:
exit()
except Exception as e:
#print e
sleep(0.1)
except Exception as e:
bailout("Exception during log operation: {0}".format(e))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment