Metadata-Version: 2.4
Name: tangods-graylogger
Version: 1.1.0
Summary: A tango device server to catch logs on the old log4tango API and send them to Graylogger using GELF and HTTP.
Author-email: Antonio Bartalesi <antonio.bartalesi@gmail.com>
License-Expression: GPL-3.0-or-later
Project-URL: repository, https://gitlab.com/tango-bartalesi/graylogger-tangods
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pytango
Requires-Dist: requests
Provides-Extra: test
Requires-Dist: pytest; extra == "test"
Dynamic: license-file

# The Graylogger Tango Device Server

A Tango device server to catch log messages generated by other device servers,
using the traditional log4tango implementation, and redirect them to Graylog
using GELF HTTP.

## Repository content

* `Graylogger` tangoDS: a Tango device that can be used as a logging target.
It sends every message it receives to Graylog over HTTP, in GELF format.
See [Graylogger](#graylogger) below.

* `LogProducer` tangoDS: a software Tango device that has commands for
producing log messages using the various `*_stream` methods
(`self.debug_stream()`, `self.error_stream()` etc...).
It also has a wrapper for exceptions that catches a generic exception, alters
state and status, sends to `self.error_stream()` and re-raises them.

* A docker compose stack (`docker/docker-compose.yml`) that runs Graylog with
MongoDB and OpenSearch. See [Docker stack](#docker-stack) below.

* A Graylog configuration file: `docker/config/graylog/graylog.conf`. This is
mostly to tune the container performance.

## Installation

```
pip install tangods-graylogger
```

This installs two scripts, `Graylogger` and `Logproducer`, that start the
device servers: `Graylogger <instance>`.

## Graylogger

To send the logs of a device to Graylog, add `device::my/gray/logger` to its
`logging_target` property, where `my/gray/logger` is the Tango name of your
Graylogger device. In the Graylogger device, set the `host` and `port`
properties to point to your Graylog server. In Graylog you must set up an
input that processes GELF HTTP requests. The default port is `12201`.

Messages are queued and sent by a background thread, so a slow or unreachable
Graylog does not block Graylogger or the devices logging to it.

Graylogger can be its own logging target, at any logging level: its own
messages (for example the warnings of the commands below) then go to Graylog
like those of any other device.

### Properties

| Property | Default | Description |
|---|---|---|
| `host` | `localhost` | Graylog host |
| `port` | `12201` | Graylog GELF HTTP input port |
| `timeout` | `0.5` | Timeout in seconds for each HTTP post to Graylog |
| `queue_size` | `1000` | Messages that can wait to be sent; further ones are dropped |

### Attributes

| Attribute | Description |
|---|---|
| `logged_messages` | Messages Graylog accepted (HTTP 202) |
| `failed_messages` | Messages that were malformed, or that Graylog refused or could not be reached for |
| `dropped_messages` | Messages dropped because the send queue was full, or still queued at `Init` |
| `last_time_log` | When the last message was received |

The state is `RUNNING` after a message is sent, and `FAULT` with the reason in
the status after a failure, until the next message is sent.

### Commands

All commands act on the *safe devices* (see below). A device that fails is
reported with a warning and skipped; the command carries on with the others.

| Command | Argument | Effect |
|---|---|---|
| `reset_logging_targets` | none | Removes and re-adds Graylogger as logging target on every device that has it in its `logging_target` property or in its current targets. Runs automatically when the server starts and on `Init`. |
| `acquire_logging_targets` | none | Adds Graylogger as logging target on every safe device, whatever its configuration. |
| `impose_all_logging_levels` | level | Sets the logging level of every device currently logging to Graylogger. |
| `impose_logging_levels_from_property` | level or `IGNORE` | For every device logging to Graylogger, or configured to, applies its `logging_level` property. Devices without the property get the given level, or are left alone with `IGNORE`. |
| `status_report` | none | Returns the `logging_target` and `logging_level` properties and the current targets and level of every safe device. |

Levels are `OFF`, `FATAL`, `ERROR`, `WARNING`, `INFO` and `DEBUG`. In the
`logging_level` property, they can also be written in any case or as a number
from 0 (`OFF`) to 5 (`DEBUG`).

Target names are compared ignoring case and surrounding spaces.

The commands need a connection to the Tango database; without one they fail
with an error asking to fix it and run `Init`.

### Safe devices

The commands only act on devices that are exported in the Tango database,
answer, and are not of one of these classes (`NO_LOG_CLASSES`):

* `DServer`, the admin devices;
* Sardana pool classes: `Pool`, `Controller`, `Motor`, `IORegister`,
  `CTExpChannel`, `ZeroDExpChannel`, `OneDExpChannel`, `TwoDExpChannel`,
  `PseudoMotor`, `PseudoCounter`, `TriggerGate`, `MotorGroup`,
  `MeasurementGroup`;
* Sardana macroserver classes: `MacroServer`, `Door`;
* `LogConsumer`, the temporary log consumers of Jive.

Devices are contacted in parallel. A device that is exported but hangs costs
about 6 seconds (Tango's connection timeout, twice), however many there are,
so a command can still exceed a client's default 3 second timeout. Increase it
on the client when calling the commands on a large or unhealthy system.

## Docker stack

To start Graylog, start systemd `docker.service`, then navigate to the
`docker` directory and run `docker compose up`. Stop with `<Ctrl-C>`. The
messages and settings are stored in docker volumes. To revert to a blank
installation, run `docker compose down -v` when not running. To log in, go to
`localhost:9000` and log in as `admin`, password `password12345`.

## Observations and annotations

Graylog was chosen because it is very convenient for log analysis. The GELF
protocol was chosen for its simplicity (only a few items are mandatory) and
because it is possible to extend it with other tags: the user defined tags
simply start with an underscore. HTTP was chosen because it's simple to
implement and because the server replies to post requests, making it possible
to know if the log was sent successfully. It is also possible to switch to
HTTPS for enhanced security, even if that is not implemented yet.

A good place for tango logging documentation is the
[RFC](https://tango-controls.readthedocs.io/projects/rfc/en/latest/14/Logging.html).

Tango logging has room for improvement. The amount of information and format is
limited and not all features are implemented. Exceptions are not added to the
logs automatically, not even if changing the `logging_level`: changes to the
code are necessary. The easiest way to do so in python is to use wrappers.
See `log_exceptions` in `LogProducer`.

The methods that are named `debug_stream()` and similar are not really streams,
they are *loggers*.

If you start a tango device with `-v3` or `-v5` the logging behavior changes
completely: `logging_target` and `logging_level` are overridden. -v5 adds extra
corba logs to the stream. The corba logs are not documented (AFAIK).

It is not entirely possible to set the logging target in jive, as multi stream
requires a multi line property that is not possible to input in jive. One way
to do so, is by using pytango `Database()` class.

`itango` example:
`Database().put_device_property('my/log/producer', {"logging_target":
['console', 'file::/home/me/test.log', 'device::my/gray/logger']})`.

This adds 3 logging targets, one to console, one to file and one to another
tango device.

Tango stores logging targets in lower case, including file paths.

If the logging target tangoDS is restarted, the whole logging will stop.
It is not possible to initialize the devices in order, they have to be
restarted, because the logging is set in a stage before the init itself.
The tango device which acts as a log target needs to be started first, then all
the other devices can start. This is an important limitation. It could be worth
looking into file based approaches.

To work around these limitations, Graylogger runs `reset_logging_targets` when
it starts and on `Init`, and has commands to reset the logging of the other
devices.

Sardana seems to do things differently, it does not seem to respond to
`set_logging_target()` and `set_logging_level()`. It uses standard python
logging. I was unable to use a device or console target.
