- Удаленное логирование в journald или Всё ещё «это вам не нужно»?
- Дисклеймер
- Вводная часть
- Преамбула
- Головной хост
- systemd-journal-remote
- Дьявол в деталях
- systemd-journal-upload
- Дьявол в деталях
- Удаленные клиенты
- systemd-journal-gatewayd
- Дьявол в деталях
- Дойдём до конца!
- Итого
- How to Setup Rsyslog Remote Logging on Linux
- Installation
- Configuration Structure
- Modules
- Configuration Directives
- Rule Line
- A Sample Configuration
- Templates
- Check Rsyslog Configuration
- Send Sample Data
- How to Setup Rsyslog Remote Logging on Linux (Central Log Server)
- Installation
- Configuration Structure
- Modules
- Configuration Directives
- Rule line
- A Sample Configuration
- Templates
- Central Logging Server
Удаленное логирование в journald или Всё ещё «это вам не нужно»?
Дисклеймер
Все эксперименты проводились на CentOS Linux release 7.2.1511 в качестве основной системы, с последними доступными из стоковой репы systemd (systemd-219-19.el7_2.13). Надеюсь, часть приведенных данных будет неактуальна уже на момент публикации статьи.
Вводная часть
Начав захватывать linux-дистрибутивы с выпуска Fedora 15, systemd окончательно победил. Зубры и аксакалы понемногу приучаются к unit’ам и systemctl. Скрежещат зубами последние защитники Старого Доброго. В этих реалиях невозможно обойти дочерние продукты systemd. И сегодня давайте поговорим, например, про journald.
Сам по себе journald (и соответственно journalctl) — прекрасный инструмент. Зародившийся как слегка сторонний к systemd проект, к нынешнему времени journald стал вторым инструментом из семейства systemd, с которым знакомятся системные администраторы. Мне действительно нравится идея рантайм хранилища логов с опциональной возможностью сброса на постоянное хранение, задумка с boot-id journalctl —boot и machine-id ( journalctl —machine ), возможность из единого интерфейса вызывать логи любых зарегистрированных приложений journalctl -u , а также наличие «из коробки» ротации логов (как по месту, так и по времени) при помощи journalctl —vacuum-size или journalctl —vacuum-time . Из хорошего нельзя не упомянуть ещё и параметры since , until и priority , которыми можно «грепать» события по времени и приоритету, и, разумеется, параметр utc , снимающий огромную головную боль с мульти-таймзонными командами и проектами. Может быть немного спорным бинарный формат хранения файлов, но этот выбор был объяснен авторами ещё при первых анонсах journald (безопасность и дешевизна хранения, интеграция с systemd, принудительный единый формат, переносимость).
К сожалению, не приобрел большого распространения механизм каталогов journald, который позволяет, например, организовать перевод сообщений логов или предоставить конечным пользователям url для решения проблем с конкретными ошибками. Но в целом даже разработчики systemd не пользуются этой возможностью полностью — куда уж нам, смертным.
Это всё реализовано, работает, описано в сотнях мануалов, проверено. Большое спасибо, но я хочу больше.
Преамбула
Не так давно один приятель попросил настроить ему сервер для сбора логов. Хха! — подумал я, — это же прекрасный повод изучить journald в свете его возможностей центрального лог-сервера!
Понятное дело, что инструмент зависит от задачи. Вот и в этот раз был проведен краткий сбор требований:
- Необходимо организовать единую точку логирования
- Необходимо организовать возможность подключения к единой точке логирования заранее неизвестного количества клиентов (и их отключение, соответственно)
- Желательно организовать возможность просмотра логов online, с автоматическим получением новых записей
- При выполнении предыдущего пункта, хранение логов на центральной точке можно ограничить N часами (даже не днями)
- Формат сообщений непостоянен вплоть до мультилайна
- Ключевое интересующее ПО пишет в stdout (да, можно изменить поведение или накостылить, но покупаем, что продают), консоль не закрывает
И общетехническая вводная:
- Данные передаются по паблик-сетям
- Головная выделенная машина: Centos7.2 (latest)
- Подключаемые машины: Ubuntu 16.04
Кажется, что systemd и journald хороший выбор, верно? Ведь все пункты уже реализованы! Поднимаем тестовый стенд!
Головной хост
Ну что же, начнём.
Нас интересуют три компонента:
- systemd-journal-gatewayd — http-демон, открывающий порт для просмотра (или скачивания) записей журнала
- systemd-journal-remote — демон, скачивающий или принимающий записи журналов на центральном сервере
- systemd-journal-upload — демон, дублирующий записи журналов на удаленный сервер
Все эти компоненты входят в centos-пакет systemd-journal-gateway , так что выполняем:
За получение логов на головной машине используется демон systemd-journal-remote . С него и начнём.
systemd-journal-remote
У remote есть два режима работы: активный (при котором он сам ходит в удаленный журнал и скачивает логи — в том числе в режиме слежения. Для этого режима на всех удаленных машинах нужен systemd-journal-gatewayd ) и пассивный (при котором демон висит и ждёт, пока к нему придут). С учетом неизвестного количества машин — выбираем пассивный режим. Вся настройка, собственно, заключается в том, чтобы сделать директорию /var/log/journal/remote , назначить ей права нужного пользователя и запустить сервис:
Поскольку мы собираем демо-стенд, давайте переключим протокол приёма файлов с https на http. Для этого необходимо отредатировать стартовый сервис-файл /lib/systemd/system/systemd-journal-remote.service , заменив опцию listen-https на listen-http . Также будет полезно поправить /lib/systemd/system/systemd-journal-remote.socket , указав только интересующий нас адрес для биндинга демона.
Демон стартовал, висит в пассивном режиме, работает по http. Ура!
Дьявол в деталях
Во-первых, при создании директории /var/log/journal все ваши системные логи начнут писаться в директорию /var/log/journal/ . Чтобы изменить это поведение и вернуть как было, надо заправить конфигурационный файл /etc/systemd/journald.conf (а лучше даже /etc/systemd/journald.conf.d/ .conf , т.к. первый может перетереться при обновлениях), а именно строку Storage= . По умолчанию, значение этого параметра auto , что означает «если есть директория в var, journald записывает логи туда». В моём случае, параметр надо было принудительно выставить в volatile .
systemd-journal-upload
С upload всё ещё проще: создаём /etc/systemd/journal-upload.d/ .conf , записав туда:
и запустим systemctl start systemd-journal-upload
Дьявол в деталях
Во-вторых, демон не запустится благодаря очень старой баге в Centos. Так что делайте usermod руками: usermod -a -G systemd-journal systemd-journal-upload . После этого демон должен стартовать успешно.
Удаленные клиенты
На удаленных клиентах, напомню, стоит Ubuntu 16.04. Так что ставим там apt-get install systemd-journal-remote и проводим правки /etc/systemd/journal-upload.d/ .conf , аналогичные предыдущему пункту (кроме usermod ).
systemd-journal-gatewayd
А тут, собственно, описывать нечего. Текущая версия, представленная в Centos, не позволяет указывать нестандартные директории для указанного демона. Причем стандартная директория для логов с других машин, по логике разработчиков, является нестандартной для просмотрщика логов. В новых версиях systemd это, кажется, исправлено, но мы же не будем ставить неродные версии.
Ну что же, давайте хотя бы понаблюдаем за логами:
Ну, что-то вроде работает.
Дьявол в деталях
В третьих, благодаря старой баге в systemd, у вас начнёт дичайше пухнуть директория /var/log/journal/remote . И тут вам не поможет ничего.
Дойдём до конца!
Тем не менее, раз уж мы зашли так далеко, давайте дойдём до конца. Запускаем на головной машине демон systemd-journal-gatewayd (опять не забываем поправить /lib/systemd/system/systemd-journal-gatewayd.socket , чтобы ограничить демона, да?) и внимательно изучаем веб-интерфейс просмотрщика:
- Подкачка логов online фактически отсутствует
- Лютые on mouse over и on mouse scroll для логов
- microhttpd под капотом
- Простите, но ужасающий интерфейс
- Есть возможность фильтрации логов по systemd-unit, но (в связи с количеством неинформативных session-юнитов например от крон-скриптов) невозможность пользоваться фильтрами
- Все юниты пишутся полностью — если вы используете например пароли к базам данных в крон-строках, ваши пароли будут вас ждать
Нда. Возможно, и хорошо, что не получилось его настроить, м?
Итого
Для proof of concept за пару дней был написан pet-проект, благо journald предоставляет родную библиотеку для питона. Из особенностей:
- Онлайн-просмотр по SSE
- Возможность фильтровать выводимые юниты администратором на уровне конфигурации
- Возможность фильтровать хосты/приоритет/юниты пользователем на уровне веб-приложения
- Ну и немножко бутстрапа
Этот же проект был раскатан приятелю, с описанием имеющихся проблем, отказом от ответственности и принудительной очисткой журналов.
Но на больших проектах лично я наверное ещё долго не буду использовать journald в качестве центрального хранилища логов. До тех пор, пока не будут убраны приведенные выше баги, мой выбор — однозначно в пользу syslog.
Источник
How to Setup Rsyslog Remote Logging on Linux
Every Linux distribution comes with some logging systems to record system activities. This might be helpful during system troubleshooting. Rsyslog is an open source and is rocket-fast in terms of speed for system log process. It is available for several major Linux distributions including Debian and Red Hat based systems. Compared to SYSLOG protocol, It has several additional features such as content-based filtering of TCP for transporting and provides tons of configuration options. This article describes how to setup Rsyslog Remote Logging in simple steps.
Installation
If Rsyslog is not installed on your linux system, install using the following command −
The output should be like this −
Rsyslog configurations are stored in /etc/ryslog.conf file and the files will be under /etc/rsyslog.d/ directory.
Configuration Structure
The structure of Rsyslog configuration files are in the following manner −
- Modules
- Configuration Directives
- Rule Line
Modules
Rsyslog has a modular architecture. It will enable functionality in a dynamic manner. The modules are categorized into the following manner −
- Input Modules – Used to gather messages from various sources.
- Output Modules – Used to write the messages to various places ( file, socket etc.. ).
- Parser Modules – Used to parse the message content.
Configuration Directives
Configuration directives are the configuration instructions for Rsyslog. These should be specified only one per a line which starts with dollar ($) symbol.
Rule Line
Each Rule line consists of two fields, they are divided as selector field and an action field. Again the selector field is divided into two fields, it should be like this −
A Sample Configuration
Templates
It is the most important feature of Rsyslog which allows the user to log the messages in a desirable format. It can also be used to create dynamic file names to log the messages.
Check Rsyslog Configuration
Before checking Rsyslog configuration, make sure that you have restarted Rsyslog so that your changes can take immediate effect. To restart Rsyslog, use the following command −
Make sure Rsyslog is running. If this command returns nothing, then we can assume that, it is not running at all. Use the following command to check if the process is running –
A sample output should be like this −
Check the Rsyslog configuration, use the following command −
The sample output should be like this −
Check Linux system logs for any Rsyslog errors. If there are errors you can find them in /var/log/messages. Some logs may also stored be in /var/log/syslog.
Send Sample Data
Verify Rsyslog is sending data to logger by creating a test event. To send the data, use the following command –
Check linux system logs to see if Rsyslog has recorded the test event, To verify it, use the following command –
A sample output should be like this −
Congratulations! Now, you know “How to Setup Rsyslog Remote Logging” on Linux. We’ll learn more about these type of commands in our next Linux post. Keep reading!
Источник
How to Setup Rsyslog Remote Logging on Linux (Central Log Server)
Every Linux distribution have some kind of logging mechanism that records all the system activities. A while back we provided a list of 20 log files that are stored under /var/log that you might be helpful during troubleshooting. These logs are very critical for sysadmin for troubleshooting purpose.
The following are the three common methods to log a message:
- Logging on the same server: Messages get written into the local hard drive/local database
- Logging on a remote server: Many systems forward their logs over the network to a central log server. On the central log server, the messages from various systems are written to the local hard drive/database.
- Relay logging: Branch ‘A’ and Branch ‘B’ logs the messages on 2 different servers. These server in-turn logs the message to the ‘Head Office’.
Rsyslog is the default logging program on several Linux distributions including Debian and Red Hat based systems. Apart from implementing the syslog protocol, rsyslog adds additional features such as content-based filtering. This also uses TCP for transporting, and provides lot of configuration options.
This article explains how to implement the method 2 mentioned above. i.e This explains how to setup a central logging server, and send logs from individual servers to the central logging server.
This setup will help you to analyze the log files of all the servers in your infrastructure from a central log server.
Installation
Rsyslog comes as the default logging program in Debian Distribution and Red Hat based systems. If you system doesn’t have rsyslog, install it as shown below depending on your distro.
Rsyslog configurations are stored in /etc/ryslog.conf file and the files under /etc/rsyslog.d/ directory.
Configuration Structure
Before understanding how to setup the central logging sever, it is good to understand the configuration structure of rsyslog.
Rsyslog configuration files are structed in the following manner
- Modules
- Configuration Directives
- Rule line
Modules
Rsyslog has a modular architecture. It enables functionalities to be added dynamically through these modules. The modules are categorized as:
- Input Modules – Used to gather messages from various sources
- Output Modules – Used to write the messages to various places ( file, socket etc.. )
- Parser Modules – Used to parse the message content
Please note that there are also other categories of modules available. This is to give an overview of what modules can do.
Configuration Directives
All configuration directives must be specified one per line and must start with dollar sign ($). It affects the rules.
Rule line
Every rule line consists of two fields, a ‘selector field’ and an ‘action field’. The selector field is divided into two, ‘facilities & priorities’. Action specifies what action must be taken for the matched rule.
A Sample Configuration
Note: 10 Examples for Viewing Huge Log Files in Linux might be helpful when you are manipulating log files.
Templates
Templates are a very important features provided by rsyslog. It allows the user to log the messages in their desirable format. It can also be used to create dynamic file names to log the messages. In case of database logging, the templates are used to convert the message into a proper SQL statement.
A sample template will look like:
The above template will log the message “This is hello from rsyslog” as:
We will see how to use the template for generate the log files dynamically.
Central Logging Server
The above sections should have given an overview about rsyslog and how to configure it. Now we will move on to setup a central logging system.
For our discussion we will have server IP as “192.168.1.1” for the central log server, where all the log messages from client should be forwarded.
Add the following lines to the rsyslog.conf of the central log server servers (In this example, the following line was added on the log server with ip-address 192.168.1.1):
After adding the above lines to the rsyslog.conf, restart the rsyslog process. Now the rsyslog server will be ready to accept messages.
Add the following lines to the rsyslog.conf on the individual client machines that should send their log messages to the central server.
Restart the rsyslog process on the clients. Now the rsyslog central server (In this example, 192.168.1.1) will receive all the log messages from the configured clients and each client’s log will be placed under a separate directory.
Источник