About

This guide has been setup and tested using both the Python 2.7 (64-bit) and Python 3.6 (64-bit) environments.

Code samples included can be used inside a basic Python script, or web framework such as Django or Flask.

To send logs to logstash through Python you will need the python-logstash-async (version 1.4.1) Python plugin.

Installing

Execute the following command using pip:

pip install python-logstash-async
  If you receive errors suggesting pip is an unknown command, navigate to its installed location with your chosen terminal program and try again (or add pip to your environmental variables if using Windows).

Sending Logs

Add your imports to the top of your Python file (the file you wish to include logging on):

import logging
from logstash_async.handler import AsynchronousLogstashHandler

Add this code somewhere inside the same file (for example, this could be before Django or Flask renders a view):

# Create the logger and set it's logging level
logger = logging.getLogger("logstash")
logger.setLevel(logging.ERROR)

# Create the handler
handler = AsynchronousLogstashHandler(
    host=your-logstash-host, 
    port=your-port, 
    ssl_enabled=True, 
    ssl_verify=False,
    database_path='')

# Here you can specify additional formatting on your log record/message
formatter = LogstashFormatter()
handler.setFormatter(formatter)

# Assign handler to the logger
logger.addHandler(handler)

# Send log records to Logstash 
logger.error('python-logstash-async: test error message.')
logger.info('python-logstash-async: test info message.')
logger.warning('python-logstash-async: test warning message.')
logger.debug('python-logstash-async: test debug message.')