This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

python: Write custom Python destinations

The Python destination allows you to write your own destination in Python. You can import external Python modules to process the messages, and send them to other services or servers. Since many services have a Python library, the Python destination makes integrating AxoSyslog very easy and quick.

The following points apply to using Python blocks in AxoSyslog in general:

  • Python parsers and template functions are available in AxoSyslog version 3.10 and later.

    Python destinations and sources are available in AxoSyslog version 3.18 and later.

  • Supported Python versions: 2.7 and 3.4+ (if you are using pre-built binaries, check the dependencies of the package to find out which Python version it was compiled with).

  • The Python block must be a top-level block in the AxoSyslog configuration file.

  • If you store the Python code in a separate Python file and only include it in the AxoSyslog configuration file, make sure that the PYTHONPATH environment variable includes the path to the Python file, and export the PYTHON_PATH environment variable. For example, if you start AxoSyslog manually from a terminal and you store your Python files in the /opt/syslog-ng/etc directory, use the following command: export PYTHONPATH=/opt/syslog-ng/etc.

    In production, when AxoSyslog starts on boot, you must configure your startup script to include the Python path. The exact method depends on your operating system. For recent Red Hat Enterprise Linux, Fedora, and CentOS distributions that use systemd, the systemctl command sources the /etc/sysconfig/syslog-ng file before starting AxoSyslog. (On openSUSE and SLES, /etc/sysconfig/syslog file.) Append the following line to the end of this file: PYTHONPATH="<path-to-your-python-file>", for example, PYTHONPATH="/opt/syslog-ng/etc".

  • The Python object is initiated every time when AxoSyslog is started or reloaded.

  • The Python block can contain multiple Python functions.

  • Using Python code in AxoSyslog can significantly decrease the performance of AxoSyslog, especially if the Python code is slow. In general, the features of AxoSyslog are implemented in C, and are faster than implementations of the same or similar features in Python.

  • Validate and lint the Python code before using it. The AxoSyslog application does not do any of this.

  • Python error messages are available in the internal() source of AxoSyslog.

  • You can access the name-value pairs of AxoSyslog directly through a message object or a dictionary.

  • To help debugging and troubleshooting your Python code, you can send log messages to the internal() source of AxoSyslog. For details, see Logging from your Python code.

Declaration:

Python destinations consist of two parts. The first is a AxoSyslog destination object that you define in your AxoSyslog configuration and use in the log path. This object references a Python class, which is the second part of the Python destination. The Python class processes the log messages it receives, and can do virtually anything that you can code in Python. You can either embed the Python class into your AxoSyslog configuration file, or store it in an external Python file.

   destination <name_of_the_python_destination>{
        python(
            class("<name_of_the_python_class_executed_by_the_destination>")
        );
    };
    
    python {
    class <name_of_the_python_class_executed_by_the_destination>(object):
    
        def open(self):
            """Open a connection to the target service
    
            Should return False if opening fails"""
            return True
    
        def close(self):
            """Close the connection to the target service"""
            pass
    
        def is_opened(self):
            """Check if the connection to the target is able to receive messages"""
            return True
    
        def init(self, options):
            """This method is called at initialization time
    
            Should return false if initialization fails"""
            return True
    
        def deinit(self):
            """This method is called at deinitialization time"""
            pass
    
        def send(self, msg):
            """Send a message to the target service
    
            It should return True to indicate success. False will suspend the
            destination for a period specified by the time-reopen() option."""
            return True
    
        def flush(self):
            """Flush the queued messages"""
            pass
    };

Methods of the python() destination

init(self, options) method (optional)

The AxoSyslog application initializes Python objects every time when it is started or reloaded. The init method is executed as part of the initialization. You can perform any initialization steps that are necessary for your source to work.

When this method returns with False, AxoSyslog does not start. It can be used to check options and return False when they prevent the successful start of the source.

options: This optional argument contains the contents of the options() parameter of the AxoSyslog configuration object as a Python dictionary.

is_opened(self) method (optional)

Checks if the connection to the target is able to receive messages, and should return True if it is. For details, see Error handling in the python() destination.

open(self) method (optional)

The open(self) method opens the resources required for the destination, for example, it initiates a connection to the target service. It is called after init() when AxoSyslog is started or reloaded. If send() returns with an error, AxoSyslog calls close() and open() before trying to send again.

If open() fails, it should return the False value. In this case, AxoSyslog retries it every time-reopen() seconds. By default, this is 1 second for Python sources and destinations, the value of time-reopen() is not inherited from the global option. For details, see Error handling in the python() destination.

send(self, message) method (mandatory)

The send method sends a message to the target service. It should return True to indicate success, or self.QUEUED when using batch mode. For other possible return values, see the description of the flush() method. Note that for batch mode, the flush() method must be implemented as well.

This is the only mandatory method of the destination.

If a message cannot be delivered after the number of times set in retries() (by default: 3), AxoSyslog drops the message and continues with the next message. For details, see Error handling in the python() destination.

The method can return True, False, or one of the following constants:

  • self.DROP: The message is dropped immediately.

  • self.ERROR: Corresponds to boolean False. The message is put back to the queue, and sending the message is attempted (up to the number of the retries() option). The destination is suspended for time-reopen() seconds.

  • self.SUCCESS: Corresponds to boolean True. The message was sent successfully.

  • self.QUEUED: The send() method should return this value when using batch mode, if it has successfully added the message to the batch. Message acknowledgment of batches is controlled by the flush() method.

  • self.NOT_CONNECTED: The message is put back to the queue, and the destination is suspended. The open() method will be called, and the sending the messages will be continued with the same message/batch.

  • self.RETRY: The message is put back to the queue, and sending the message is attempted (up to the number of the retries() option). If sending the message has failed retries() times, self.NOT_CONNECTED is returned.

flush(self) method (optional)

Send the messages in a batch. You can use this method to implement batch-mode message sending instead of sending messages one-by-one. When using batch mode, the send() method adds the messages to a batch (for example, a list), and the flush() method sends the messages as configured in the batch-bytes(), batch-lines(), or batch-timeout() options.

The method can return True, False, or one of the following constants:

  • self.DROP: The messages cannot be sent and the entire batch is dropped immediately.

  • self.ERROR: Corresponds to boolean False. The message is put back to the queue, and sending the message is attempted (up to the number of the retries() option). The destination is suspended for time-reopen() seconds.

  • self.SUCCESS: Corresponds to boolean True. The message was sent successfully.

  • self.NOT_CONNECTED: The message is put back to the queue, and the destination is suspended. The open() method will be called, and the sending the messages will be continued with the same message/batch.

  • self.RETRY: The message is put back to the queue, and sending the message is attempted (up to the number of the retries() option). If sending the message has failed retries() times, self.NOT_CONNECTED is returned.

close(self) method (optional)

Close the connection to the target service. Usually it is called right before deinit() when stopping or reloading AxoSyslog. It is also called when send() fails.

The deinit(self) method (optional)

This method is executed when AxoSyslog is stopped or reloaded. This method does not return a value.

Error handling in the python() destination

The Python destination handles errors as follows.

  1. Currently AxoSyslog ignores every error from the open method until the first log message arrives to the Python destination. If the fist message has arrived and there was an error in the open method, AxoSyslog starts calling the open method every time-reopen() second, until opening the destination succeeds.

  2. If the open method returns without error, AxoSyslog calls the send method to send the first message.

  3. If the send method returns with an error, AxoSyslog calls the is_opened method.

    • If the is_opened method returns an error, AxoSyslog starts calling the open method every time-reopen() second, until opening the destination succeeds.

    • Otherwise, AxoSyslog calls the send method again.

  4. If the send method has returned with an error retries() times and the is_opened method has not returned any errors, AxoSyslog drops the message and attempts to process the next message.

Example: Write logs into a file

The purpose of this example is only to demonstrate the basics of the Python destination, if you really want to write log messages into text files, use the file destination instead.

The following sample code writes the body of log messages into the /tmp/example.txt file. Only the send() method is implemented, meaning that AxoSyslog opens and closes the file for every message.

   destination d_python_to_file {
        python(
            class("TextDestination")
        );
    };
    log {
        source(src);
        destination(d_python_to_file);
    };
    python {
    class TextDestination(object):
        def send(self, msg):
            self.outfile = open("/tmp/example.txt", "a")
            self.outfile.write("MESSAGE = %s\n" % msg["MESSAGE"])
            self.outfile.flush()
            self.outfile.close();
            return True
    };

The following code is similar to the previous example, but it opens and closes the file using the open() and close() methods.

   destination d_python_to_file {
        python(
            class("TextDestination")
        );
    };
    log {
        source(src);
        destination(d_python_to_file);
    };
    python {
    class TextDestination(object):
        def open(self):
            try:
                self.outfile = open("/tmp/example.txt", "a")
                return True
            except:
                return False
    
        def send(self, msg):
            self.outfile.write("MESSAGE = %s\n" % msg["MESSAGE"])
            self.outfile.flush()
            return True
    
        def close(self):
            try:
                self.outfile.flush()
                self.outfile.close();
                return True
            except:
                return False
    };

Example: Print logs in batch mode

The following is a simple destination that uses the flush() method to print the messages in batch mode.

   class MyDestination(object):
        def init(self, options):
            self.bulk = list()
            return True
    
        def send(self, msg):
             self.bulk.append(msg["MSG"].decode())
             return self.QUEUED
    
        def flush(self):
            print("flushing: " + ",".join(self.bulk))
            self.bulk = list()
            return self.SUCCESS

For the list of available optional parameters, see python() destination options.

1 - python() destination options

The Python destination allows you to write your own destination in Python. The python() destination has the following options. The class() option is mandatory. For details on writing destinations in Python, see python: Write custom Python destinations.

batch-bytes()

Accepted values: number [bytes]
Default: none

Description: Sets the maximum size of payload in a batch. If the size of the messages reaches this value, AxoSyslog sends the batch to the destination even if the number of messages is less than the value of the batch-lines() option.

Note that if the batch-timeout() option is enabled and the queue becomes empty, AxoSyslog flushes the messages only if batch-timeout() expires, or the batch reaches the limit set in batch-bytes().

Available in AxoSyslog version 3.19 and later.

This option does not have any effect unless the flush() method is implemented in the destination.

batch-lines()

Type: number
Default: 25

Description: Specifies how many lines are flushed to a destination in one batch. The AxoSyslog application waits for this number of lines to accumulate and sends them off in a single batch. Increasing this number increases throughput as more messages are sent in a single batch, but also increases message latency.

For example, if you set batch-lines() to 100, AxoSyslog waits for 100 messages.

If the batch-timeout() option is disabled, the AxoSyslog application flushes the messages if it has sent batch-lines() number of messages, or the queue became empty. If you stop or reload AxoSyslog or in case of network sources, the connection with the client is closed, AxoSyslog automatically sends the unsent messages to the destination.

Note that if the batch-timeout() option is enabled and the queue becomes empty, AxoSyslog flushes the messages only if batch-timeout() expires, or the batch reaches the limit set in batch-lines().

For optimal performance, make sure that the AxoSyslog source that feeds messages to this destination is configured properly: the value of the log-iw-size() option of the source must be higher than the batch-lines()*workers() of the destination. Otherwise, the size of the batches cannot reach the batch-lines() limit.

This option does not have any effect unless the flush() method is implemented in the destination.

batch-timeout()

Type: time in milliseconds
Default: -1 (disabled)

Description: Specifies the time AxoSyslog waits for lines to accumulate in the output buffer. The AxoSyslog application sends batches to the destinations evenly. The timer starts when the first message arrives to the buffer, so if only few messages arrive, AxoSyslog sends messages to the destination at most once every batch-timeout() milliseconds.

This option does not have any effect unless the flush() method is implemented in the destination.

class()

Type: string
Default: N/A

Description: The name of the Python class that implements the destination, for example:

   python(
        class("MyPythonDestination")
    );

If you want to store the Python code in an external Python file, the class() option must include the name of the Python file containing the class, without the path and the .py extension, for example:

   python(
        class("MyPythonfilename.MyPythonDestination")
    );

For details, see Python code in external files

disk-buffer()

Description: This option enables putting outgoing messages into the disk buffer of the destination to avoid message loss in case of a system failure on the destination side. It has the following options:

capacity-bytes()

Type: number (bytes)
Default: 1MiB

Description: This is a required option. The maximum size of the disk-buffer in bytes. The minimum value is 1048576 bytes. If you set a smaller value, the minimum value will be used automatically. It replaces the old log-disk-fifo-size() option.

In AxoSyslog version 4.2 and earlier, this option was called disk-buf-size().

compaction()

Type: yes/no
Default: no

Description: If set to yes, AxoSyslog prunes the unused space in the LogMessage representation, making the disk queue size smaller at the cost of some CPU time. Setting the compaction() argument to yes is recommended when numerous name-value pairs are unset during processing, or when the same names are set multiple times.

dir()

Type: string
Default: N/A

Description: Defines the folder where the disk-buffer files are stored.

flow-control-window-bytes()

Type: number (bytes)
Default: 163840000

Description: Use this option if the option reliable() is set to yes. This option contains the size of the messages in bytes that is used in the memory part of the disk buffer. It replaces the old log-fifo-size() option. It does not inherit the value of the global log-fifo-size() option, even if it is provided. Note that this option will be ignored if the option reliable() is set to no.

In AxoSyslog version 4.2 and earlier, this option was called mem-buf-size().

flow-control-window-size()

Type: number(messages)
Default: 10000

Description: Use this option if the option reliable() is set to no. This option contains the number of messages stored in overflow queue. It replaces the old log-fifo-size() option. It inherits the value of the global log-fifo-size() option if provided. If it is not provided, the default value is 10000 messages. Note that this option will be ignored if the option reliable() is set to yes.

In AxoSyslog version 4.2 and earlier, this option was called mem-buf-length().

front-cache-size()

Type: number(messages)
Default: 1000

Description: The number of messages stored in the output buffer of the destination. Note that if you change the value of this option and the disk-buffer already exists, the change will take effect when the disk-buffer becomes empty.

Options reliable() and capacity-bytes() are required options.

In AxoSyslog version 4.2 and earlier, this option was called qout-size().

prealloc()

Type: yes/no
Default: no

Description:

By default, AxoSyslog doesn’t reserve the disk space for the disk-buffer file, since in a properly configured and sized environment the disk-buffer is practically empty, so a large preallocated disk-buffer file is just a waste of disk space. But a preallocated buffer can prevent other data from using the intended buffer space (and elicit a warning from the OS if disk space is low), preventing message loss if the buffer is actually needed. To avoid this problem, when using AxoSyslog 4.0 or later, you can preallocate the space for your disk-buffer files by setting prealloc(yes).

In addition to making sure that the required disk space is available when needed, preallocated disk-buffer files provide radically better (3-4x) performance as well: in case of an outage the amount of messages stored in the disk-buffer is continuously growing, and using large continuous files is faster, than constantly waiting on a file to change its size.

If you are running AxoSyslog on a dedicated host (always recommended for any high-volume settings), use prealloc(yes).

Available in AxoSyslog 4.0 and later.

reliable()

Type: yes/no
Default: no

Description: If set to yes, AxoSyslog cannot lose logs in case of reload/restart, unreachable destination or AxoSyslog crash. This solution provides a slower, but reliable disk-buffer option. It is created and initialized at startup and gradually grows as new messages arrive. If set to no, the normal disk-buffer will be used. This provides a faster, but less reliable disk-buffer option.

truncate-size-ratio()

Type: number((between 0 and 1))
Default: 1 (do not truncate)

Description: Limits the truncation of the disk-buffer file. Truncating the disk-buffer file can slow down the disk IO operations, but it saves disk space. By default, AxoSyslog version 4.0 and later doesn’t truncate disk-buffer files by default (truncate-size-ratio(1)). Earlier versions freed the disk-space when at least 10% of the disk-buffer file could be freed (truncate-size-ratio(0.1)).

AxoSyslog only truncates the file if the possible disk gain is more than truncate-size-ratio() times capacity-bytes().

  • Smaller values free disk space quicker.
  • Larger ratios result in better performance.

If you want to avoid performance fluctuations:

Example: Examples for using disk-buffer()

In the following case reliable disk-buffer() is used.

destination d_demo {
    network(
        "127.0.0.1"
        port(3333)
        disk-buffer(
            flow-control-window-bytes(10000)
            capacity-bytes(2000000)
            reliable(yes)
            dir("/tmp/disk-buffer")
        )
    );
};

In the following case normal disk-buffer() is used.

destination d_demo {
    network(
        "127.0.0.1"
        port(3333)
            disk-buffer(
            flow-control-window-size(10000)
            capacity-bytes(2000000)
            reliable(no)
            dir("/tmp/disk-buffer")
        )
    );
};

frac-digits()

Type: number
Default: 0

Description: The AxoSyslog application can store fractions of a second in the timestamps according to the ISO8601 format. The frac-digits() parameter specifies the number of digits stored. The digits storing the fractions are padded by zeros if the original timestamp of the message specifies only seconds. Fractions can always be stored for the time the message was received.

loaders()

Type: list of python modules
Default: empty list

Description: The AxoSyslog application imports Python modules specified in this option, before importing the code of the Python class. This option has effect only when the Python class is provided in an external Python file. This option has no effect when the Python class is provided within the AxoSyslog configuration file (in a python{} block). You can use the loaders() option to modify the import mechanism that imports Python class. For example, that way you can use hy in your Python class.

   python(class(usermodule.HyParser) loaders(hy))

log-fifo-size()

Type: number
Default: Use global setting.

Description: The number of messages that the output queue can store.

on-error()

Type: One of: drop-message, drop-property, fallback-to-string, silently-drop-message, silently-drop-property, silently-fallback-to-string
Default: Use the global setting (which defaults to drop-message)

Description: Controls what happens when type-casting fails and AxoSyslog cannot convert some data to the specified type. By default, AxoSyslog drops the entire message and logs the error. Currently the value-pairs() option uses the settings of on-error().

  • drop-message: Drop the entire message and log an error message to the internal() source. This is the default behavior of AxoSyslog.
  • drop-property: Omit the affected property (macro, template, or message-field) from the log message and log an error message to the internal() source.
  • fallback-to-string: Convert the property to string and log an error message to the internal() source.
  • silently-drop-message: Drop the entire message silently, without logging the error.
  • silently-drop-property: Omit the affected property (macro, template, or message-field) silently, without logging the error.
  • silently-fallback-to-string: Convert the property to string silently, without logging the error.

options()

Type: string
Default: N/A

Description: This option allows you to pass custom values from the configuration file to the Python code. Enclose both the option names and their values in double-quotes. The Python code will receive these values during initialization as the options dictionary. For example, you can use this to set the IP address of the server from the configuration file, so it is not hard-coded in the Python object.

   python(
        class("MyPythonClass")
        options(
            "host" "127.0.0.1"
            "port" "1883"
            "otheroption" "value")
    );

For example, you can refer to the value of the host field in the Python code as options["host"]. Note that the Python code receives the values as strings, so you might have to cast them to the type required, for example: int(options["port"])

persist-name()

Type: string
Default: N/A

Description: If you receive the following error message during AxoSyslog startup, set the persist-name() option of the duplicate drivers:

Error checking the uniqueness of the persist names, please override it with persist-name option. Shutting down.

This error happens if you use identical drivers in multiple sources, for example, if you configure two file sources to read from the same file. In this case, set the persist-name() of the drivers to a custom string, for example, persist-name("example-persist-name1").

throttle()

Type: number
Default: 0

Description: Sets the maximum number of messages sent to the destination per second. Use this output-rate-limiting functionality only when using disk-buffer as well to avoid the risk of losing messages. Specifying 0 or a lower value sets the output limit to unlimited.

time-reopen()

Accepted values: number [seconds]
Default: 1

Description: The time to wait in seconds before a dead connection is reestablished.

value-pairs()

Type: parameter list of the value-pairs() option
Default: scope("selected-macros" "nv-pairs")

Description: The value-pairs() option creates structured name-value pairs from the data and metadata of the log message. For details on using value-pairs(), see Structuring macros, metadata, and other value-pairs.

You can use this option to limit which name-value pairs are passed to the Python code for each message. Note that if you use the value-pairs() option, the Python code receives the specified value-pairs as a Python dict. Otherwise, it receives the message object. In the following example, only the text of the log message is passed to Python.

   destination d_python_to_file {
        python(
            class("pythonexample.TextDestination")
            value-pairs(key(MESSAGE))
        );
    };