Skip to content

Instantly share code, notes, and snippets.

@derlinkshaender
Created July 14, 2013 20:16
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save derlinkshaender/5995776 to your computer and use it in GitHub Desktop.
Save derlinkshaender/5995776 to your computer and use it in GitHub Desktop.
Log message to graylog using Python and the graypy package.

graylogger

Introduction

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

Usage

The help option -h displays the usage page:

./graylogger.py -h

usage: graylogger.py [options] SERVER MESSAGE

send a message to a graylog server

positional arguments:
  server                graylog server name
  message               message being sent or @FILENAME to read from FILENAME
                          or - to read from StdIn

optional arguments:
  -h, --help            show this help message and exit
  -l {DEBUG,INFO,WARNING,CRITICAL,ERROR}, --level {DEBUG,INFO,WARNING,CRITICAL,ERROR}
                        log level (defaults to ALERT)
  -f FACILITY, --facility FACILITY
                        facility name (defaults to 'PythonLogger')
  -p PORT, --port PORT  graylog port (defaults to 12201)
  -d DATA, --data DATA  additional data field (key:value)

Custom fields

Use the -d (or --data) option to supply additional fields to graylogger. The value consists of the field name and the field value, separated by a comma. If the field name or value contain white space, make sure to quote the fiel data (e.g. -d "Merchant:ACME Inc."). Separator is the first comma, so it is perfectly to valid to have a comma in the field value string. You may provide an arbitrary number of -d options as shown below:

./graylogger.py -l DEBUG -f "ETL" graylog.company.example.com "Start pricing ETL job" -d "Merchant:ACME Inc." -d Database:pricing_prod

Examples

Using a message string

The message parameter is a string. If you have whitespace in the string, be sure to enclose it in quotes:

./graylogger.py -l DEBUG -f "ETL" graylog.company.example.com "Processing startet at `date +%s`"

Piping to graylogger

Using a single dash character - as the message, graylogger will read from standard input:

output_generating_program | ./graylogger.py -l INFO -f "ETL" graylog.company.example.com -

Reading from a file

If the first character of the message parameter is a @, the message will be read from the file name directly following the @, e.g. @result.txt. If needed, a path may be specified (e.g. @/tmp/some/file.log):

./graylogger.py -l WARNING -f "ETL" graylog.company.example.com @warnings.txt

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
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,
"message": None,
"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("message", help="message being sent or @FILENAME to read from FILENAME or - to read from StdIn")
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
# process message, may be a string, a file ref starting with '@'
# or a dash to read from stdin
if args.message.startswith('@'):
fname = args.message[1:]
if os.path.exists(fname):
cmdline_options['message'] = open(fname).read()
else:
bailout('file {0} not found'.format(fname))
else:
if args.message.strip() == '-':
cmdline_options['message'] = sys.stdin.read()
else:
cmdline_options['message'] = args.message
# 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']
my_logger.log(args['level'], args['message'], extra=d)
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