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

Warning If you reload AxoSyslog, existing Python objects are destroyed, therefore the context and state information of Python blocks is lost. Log rotation and updating the configuration of AxoSyslog typically involves a reload. 

  * 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](../../docs/axosyslog-core/chapter-configuration-file/python-code-logging/index.md).




Note

Starting with 3.26, AxoSyslog assigns a persist name to Python sources and destinations. The persist name is generated from the class name. If you want to use the same Python class multiple times in your AxoSyslog configuration, add a unique `persist-name()` to each source or destination, otherwise AxoSyslog will not start. For example:
```
 
       log {
            source { python(class(PyNetworkSource) options("port" "8080") persist-name("<unique-string>); };
            source { python(class(PyNetworkSource) options("port" "8081")); };
        };
    
```

Alternatively, you can include the following line in the Python package: `@staticmethod generate_persist_name`. For example:
```
 
       from syslogng import LogSource
          class PyNetworSource(LogSource):
            @staticmethod
            def generate_persist_name(options):
                return options["port"]
            def run(self):
                pass
            def request_exit(self):
                pass
    
```

## 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](../../docs/axosyslog-core/chapter-configuration-file/python-code-external-file/index.md).
```
 
       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
        };
    
```

Note From version 3.27, AxoSyslog supports the arrow syntax in declaration. For more information, see [the options() of the python() destination](../../docs/axosyslog-core/chapter-destinations/python-destination/reference-destination-python/index.md#python-options). 

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

Warning If you reload AxoSyslog, existing Python objects are destroyed, therefore the context and state information of Python blocks is lost. Log rotation and updating the configuration of AxoSyslog typically involves a reload. 

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](../../docs/axosyslog-core/chapter-destinations/python-destination/index.md#python-destination-error-handling).

## 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](../../docs/axosyslog-core/chapter-destinations/python-destination/index.md).

## 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](../../docs/axosyslog-core/chapter-destinations/python-destination/index.md#python-destination-method-flush). 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](../../docs/axosyslog-core/chapter-destinations/python-destination/index.md#python-destination-error-handling).

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.

Warning If you reload AxoSyslog, existing Python objects are destroyed, therefore the context and state information of Python blocks is lost. Log rotation and updating the configuration of AxoSyslog typically involves a reload. 

## 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](../../docs/axosyslog-core/chapter-destinations/configuring-destinations-file/index.md) 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](../../docs/axosyslog-core/chapter-destinations/python-destination/reference-destination-python/index.md).

* * *

[python() destination options](../../docs/axosyslog-core/chapter-destinations/python-destination/reference-destination-python/index.md)

Last modified December 18, 2024: [Remove some blog references (8ac1b4c)](<https://github.com/axoflow/axosyslog-core-docs/commit/8ac1b4c55b9011c73643ba9118d8930d432a3aef>)