admin / 17.10.2018

ЕЩЕ РАЗ О ХРАНЕНИИ ЛОГОВ ZABBIX | Business Infinity Group

syslog(3) — Linux man page

Name

closelog, openlog, syslog, vsyslog — send messages to the system logger

Synopsis

#include <syslog.h>

void openlog(const char *ident, intoption, intfacility);
void syslog(int
priority, const char *format, …);
void closelog(void);

#include <stdarg.h>

void vsyslog(intpriority, const char *format, va_listap);

Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

vsyslog(): _BSD_SOURCE

Description

closelog() closes the descriptor being used to write to the system logger. The use of closelog() is optional.

openlog() opens a connection to the system logger for a program. The string pointed to by ident is prepended to every message, and is typically set to the program name. If ident is NULL, the program name is used. (POSIX.1-2008 does not specify the behavior when ident is NULL.)

The option argument specifies flags which control the operation of openlog() and subsequent calls to syslog(). The facility argument establishes a default to be used if none is specified in subsequent calls to syslog(). Values for option and facility are given below. The use of openlog() is optional; it will automatically be called by syslog() if necessary, in which case ident will default to NULL.

syslog() generates a log message, which will be distributed by syslogd(8). The priority argument is formed by ORing the facility and the level values (explained below). The remaining arguments are a format, as in printf(3) and any arguments required by the format, except that the two character sequence %m will be replaced by the error message string strerror(errno). A trailing newline may be added if needed.

The function vsyslog() performs the same task as syslog() with the difference that it takes a set of arguments which have been obtained using the stdarg(3) variable argument list macros.

The subsections below list the parameters used to set the values of option, facility, and priority.

option

The option argument to openlog() is an OR of any of these:
LOG_CONS

Write directly to system console if there is an error while sending to system logger.

LOG_NDELAY

Open the connection immediately (normally, the connection is opened when the first message is logged).

LOG_NOWAIT

Don’t wait for child processes that may have been created while logging the message. (The GNU C library does not create a child process, so this option has no effect on Linux.)

LOG_ODELAY

The converse of LOG_NDELAY; opening of the connection is delayed until syslog() is called. (This is the default, and need not be specified.)

LOG_PERROR

(Not in POSIX.1-2001 or POSIX.1-2008.) Print to stderr as well.

LOG_PID

Include PID with each message.

facility

The facility argument is used to specify what type of program is logging the message. This lets the configuration file specify that messages from different facilities will be handled differently.
LOG_AUTH

security/authorization messages

LOG_AUTHPRIV

security/authorization messages (private)

LOG_CRON

clock daemon (cron and at)

LOG_DAEMON

system daemons without separate facility value

LOG_FTP

ftp daemon

LOG_KERN

kernel messages (these can’t be generated from user processes)

LOG_LOCAL0 through LOG_LOCAL7

reserved for local use

LOG_LPR

line printer subsystem

LOG_MAIL

mail subsystem

LOG_NEWS

USENET news subsystem

LOG_SYSLOG

messages generated internally by syslogd(8)

LOG_USER (default)

generic user-level messages

LOG_UUCP

UUCP subsystem

level

This determines the importance of the message. The levels are, in order of decreasing importance:
LOG_EMERG

system is unusable

LOG_ALERT

action must be taken immediately

LOG_CRIT

critical conditions

LOG_ERR

error conditions

LOG_WARNING

warning conditions

LOG_NOTICE

normal, but significant, condition

LOG_INFO

informational message

LOG_DEBUG

debug-level message

The function setlogmask(3) can be used to restrict logging to specified levels only.

Conforming To

The functions openlog(), closelog(), and syslog() (but not vsyslog()) are specified in SUSv2, POSIX.1-2001, and POSIX.1-2008. POSIX.1-2001 specifies only the LOG_USER and LOG_LOCAL* values for facility. However, with the exception of LOG_AUTHPRIV and LOG_FTP, the other facility values appear on most UNIX systems. The LOG_PERROR value for option is not specified by POSIX.1-2001 or POSIX.1-2008, but is available in most versions of UNIX.

Notes

The argument ident in the call of openlog() is probably stored as-is. Thus, if the string it points to is changed, syslog() may start prepending the changed string, and if the string it points to ceases to exist, the results are undefined. Most portable is to use a string constant.

Never pass a string with user-supplied data as a format, use the following instead:

syslog(priority, «%s», string);

See Also

logger(1), setlogmask(3), syslog.conf(5), syslogd(8)

Referenced By

3proxy(8), agetty(8), airdaemon(1), amd(8), amd.conf(5), atd(8), atftpd(8), batcher(8), cnfsstat(8), com_err(3), controlchan(8), cron(8), ctlinnd(8), dhcpd(8), dictd(8), dkim-filter(8), dkim-filter.conf(5), dt-validate(1), explain_output(3), fetchmail(1), filedaemon(1), gfalfs(1), globus-rls-server(8), gsissh(1), hddtemp(8), hfaxd(8), hlfsd(8), hylafax-config(5), hylafax-log(5), hylafax-server(5), icmpinfo(1), initlog(1), innd(8), innfeed.conf(5), innxbatch(8), innxmit(8), inotifywait(1), ipsec_ipsec_pluto(8), ipsec_pluto(8), krb5.conf(5), lg.conf(5), libnids(3), limits.conf(5), lttng-ust(3), lvm.conf(5), mimedefang-filter(5), mon(8), newslog(5), ngircd.conf(5), nnrpd(8), opendkim(8), opendkim.conf(5), pam(8), pam.d(5), pam_access(8), pam_afs_session(5), pam_cracklib(8), pam_env(8), pam_faillock(8), pam_keyinit(8), pam_krb5(5), pam_krb5(8), pam_mapi(8), pam_pwhistory(8), pam_pwquality(8), pam_selinux(8), pam_sepermit(8), pam_ssh(8), pam_sss(8), pam_stack(8), pam_tally2(8), pam_thinkfinger(8), pam_time(8), pam_timestamp(8), pam_unix(8), pam_vsyslog(3), pam_warn(8), pcscd(8), perlmodlib(1), portmap(8), proofd(1), pure-ftpd(8), rdist(1), rdist(8), remctld(8), rnews(1), rrdcached(1), rsyslog.conf(5), rsyslogd(8), rtpproxy(8), sec(1), sendmail.sendmail(8), sensord(8), shield.conf(5), slapd(8), ssh(1), sshuttle(8), strongswan_pluto(8), sudoers(5), syslog(2), targets(5), tcpd(8), thttpd(8), time.conf(5), trickle(1), trickled(8), trickled.conf(5), try-from(8), unbound.conf(5), unilog(3), validate(1), vfs_audit(8), vfs_extd_audit(8), vfs_full_audit(8), vtund.conf(5), xfs(1), xproofd(1), yaf(1), yafscii(1), ypbind(8), ypserv(8), yum.conf(5)

На машине с zabbix-server в логе обнаружилось много ошибок:
/var/log/zabbix/zabbix_server.log

1735:20130402:101321.073 Sending list of <span style="text-decoration: underline;">active checks</span> to [<strong>10.8.12.57</strong>] failed: host [v03-b] not found 1732:20130402:101324.512 Sending list of <span style="text-decoration: underline;">active checks</span> to [<strong>10.8.12.6</strong>] failed: host [ns1] not found 1737:20130402:101325.918 Sending list of <span style="text-decoration: underline;">active checks</span> to [<strong>10.8.12.56</strong>] failed: host [v03-a] not found 1738:20130402:101354.219 Sending list of <span style="text-decoration: underline;">active checks</span> to [<strong>10.8.12.220</strong>] failed: host [mgmt01] not found

РЕШЕНИЕ
Входить на каждый клиент по IP из лога сервера и добавлять в конфигурацию zabbix-agentd опцию отключеня активной проверки и рестартовать демона.

ssh root@10.8.12.57 echo DisableActive=1 >> /etc/zabbix/zabbix-agentd.conf service zabbix-agent restart

Настройка Syslog-ng для Централизованного Сбора и Хранения Системных Событий

Syslog-ng является открытой реализацией протокола Syslog для Unix и Unix-подобных систем. Он расширяет оригинальную модель работы syslogd при помощи контент-фильтрации, богатых возможностей фильтрации, гибкойкон фигурации и добавляет новые функции, такие как TCP-транспорт. По состоянию на сегодняшний день Syslog-ng разрабатывается BalaBit IT Security Ltd. Он имеет два издания с общим кода. Первый называется Syslog-ng Open Source Edition (OSE) с лицензионным LGPL. Второй способ называется Premium Edition (PE) и имеет дополнительные плагины (модули) под проприетарной лицензией.

В случае, если у системного администратора есть несколько Linux-серверов и/или несколько управляемых коммутаторов, перед ним неизбежно встанет вопрос о настройке сервера для сбора и хранения журнальных файлов с данными о тех или иных событиях, происходящих на подконтрольных ему системах. В данной статье описывается настройка syslog-сервера syslog-ng для централизованного сбора данных от сетевого оборудования.

Настройка Linux для журналирования событий на удаленный syslog-сервер

По умолчанию конфигурационный файл содержит следующие записи:

# Log all kernel messages to the console. # Logging much else clutters up the screen. #kern.* /dev/console # Log anything (except mail) of level info or higher. # Don’t log private authentication messages! *.info;mail.none;news.none;authpriv.none;cron.none /var/log/messages # The authpriv file has restricted access. authpriv.* /var/log/secure # Log all the mail messages in one place. mail.* -/var/log/maillog # Log cron stuff cron.* /var/log/cron # Everybody gets emergency messages *.emerg * # Save news errors of level crit and higher in a special file. uucp,news.crit /var/log/spooler # Save boot messages also to boot.log local7.* /var/log/boot.log

Как и в любом конфигурационном файле Linux строки, начинающиеся с #, являются комментарием.

Внесите в данный файл следующие изменения:

# Log all kernel messages to the console. # Logging much else clutters up the screen. #kern.* /dev/console # Log anything (except mail) of level info or higher. # Don’t log private authentication messages! *.info;mail.none;news.none;authpriv.none;cron.none /var/log/messages *.info;mail.none;news.none;authpriv.none;cron.none @10.0.0.1 # The authpriv file has restricted access. authpriv.* /var/log/secure authpriv.* @10.0.0.1 # Log all the mail messages in one place. mail.* -/var/log/maillog mail.* @10.0.0.1 # Log cron stuff cron.* /var/log/cron cron.* @10.0.0.1 # Everybody gets emergency messages *.emerg * # Save news errors of level crit and higher in a special file. uucp,news.crit /var/log/spooler # Save boot messages also to boot.log local7.* /var/log/boot.log

Где вместо 10.0.0.1 подставьте IP-адрес вашего syslog-сервера.

Установка syslog-ng

При помощи yum установите пакет . Для Fedora данный пакет доступен в стандартных репозиториях, для RHEL и CentOS – в EPEL:

# yum install syslog-ng

Настройка syslog-ng

Предполагается , что IP-адрес syslog-сервера – 10.0.0.1; данные, поступающие от удаленных источников будут находиться в каталоге .

1. В каталоге создайте файл следующего содержания:

options { long_hostnames(off); keep_hostname(yes); use_dns(no); }; source s_internal { internal(); }; destination d_syslognglog { file(«/var/log/syslog-ng.log»); }; log { source(s_internal); destination(d_syslognglog); }; # Local sources source s_local { unix-dgram(«/dev/log»);}; # Local destinations destination authlog { file(«/var/log/auth.log»); }; destination syslog { file(«/var/log/syslog»); }; destination cron { file(«/var/log/cron.log»); }; destination daemon { file(«/var/log/daemon.log»); }; destination kern { file(«/var/log/kern.log»); }; destination lpr { file(«/var/log/lpr.log»); }; destination user { file(«/var/log/user.log»); }; destination uucp { file(«/var/log/uucp.log»); }; destination ppp { file(«/var/log/ppp.log»); }; destination mail { file(«/var/log/mail.log»); }; destination mailinfo { file(«/var/log/mail.info»); }; destination mailwarn { file(«/var/log/mail.warn»); }; destination mailerr { file(«/var/log/mail.err»); }; destination newscrit { file(«/var/log/news/news.crit»); }; destination newserr { file(«/var/log/news/news.err»); }; destination newsnotice { file(«/var/log/news/news.notice»); }; destination debug { file(«/var/log/debug»); }; destination messages { file(«/var/log/messages»); }; destination console { usertty(«root»); }; destination console_all { file(«/dev/tty12»); }; filter f_auth { facility(auth); }; filter f_authpriv { facility(auth, authpriv); }; filter f_syslog { not facility(authpriv, mail); }; filter f_cron { facility(cron); }; filter f_daemon { facility(daemon); }; filter f_kern { facility(kern); }; filter f_lpr { facility(lpr); }; filter f_mail { facility(mail); }; filter f_user { facility(user); }; filter f_uucp { facility(cron); }; filter f_ppp { facility(local2); }; filter f_news { facility(news); }; filter f_debug { not facility(auth, authpriv, news, mail); }; filter f_messages { level(info..warn) and not facility(auth, authpriv, mail, news); }; filter f_emergency { level(emerg); }; filter f_info { level(info); }; filter f_notice { level(notice); }; filter f_warn { level(warn); }; filter f_crit { level(crit); }; filter f_err { level(err); }; log { source(s_local); filter(f_authpriv); destination(authlog); }; log { source(s_local); filter(f_syslog); destination(syslog); }; log { source(s_local); filter(f_cron); destination(cron); }; log { source(s_local); filter(f_daemon); destination(daemon); }; log { source(s_local); filter(f_kern); destination(kern); }; log { source(s_local); filter(f_lpr); destination(lpr); }; log { source(s_local); filter(f_mail); destination(mail); }; log { source(s_local); filter(f_user); destination(user); }; log { source(s_local); filter(f_uucp); destination(uucp); }; log { source(s_local); filter(f_mail); filter(f_info); destination(mailinfo); }; log { source(s_local); filter(f_mail); filter(f_warn); destination(mailwarn); }; log { source(s_local); filter(f_mail); filter(f_err); destination(mailerr); }; log { source(s_local); filter(f_news); filter(f_crit); destination(newscrit); }; log { source(s_local); filter(f_news); filter(f_err); destination(newserr); }; log { source(s_local); filter(f_news); filter(f_notice); destination(newsnotice); }; log { source(s_local); filter(f_debug); destination(debug); }; log { source(s_local); filter(f_messages); destination(messages); }; log { source(s_local); filter(f_emergency); destination(console); }; log { source(s_local); filter(f_ppp); destination(ppp); }; log { source(s_local); destination(console_all); }; # Remote logging source s_remote { udp(ip(10.0.0.1) port(514)); }; # Remote destinations destination r_authlog { file(«/var/log/servers/$HOST/$YEAR/$MONTH/$DAY/authlog.log» owner(«root») group(«root») perm(0640) dir_perm(0750) create_dirs(yes)); }; destination r_syslog { file(«/var/log/servers/$HOST/$YEAR/$MONTH/$DAY/syslog» owner(«root») group(«root») perm(0640) dir_perm(0750) create_dirs(yes)); }; destination r_cron { file(«/var/log/servers/$HOST/$YEAR/$MONTH/$DAY/cron.log» owner(«root») group(«root») perm(0640) dir_perm(0750) create_dirs(yes)); }; destination r_daemon { file(«/var/log/servers/$HOST/$YEAR/$MONTH/$DAY/daemon.log» owner(«root») group(«root») perm(0640) dir_perm(0750) create_dirs(yes)); }; destination r_kern { file(«/var/log/servers/$HOST/$YEAR/$MONTH/$DAY/kern.log» owner(«root») group(«root») perm(0640) dir_perm(0750) create_dirs(yes)); }; destination r_lpr { file(«/var/log/servers/$HOST/$YEAR/$MONTH/$DAY/lpr.log» owner(«root») group(«root») perm(0640) dir_perm(0750) create_dirs(yes)); }; destination r_user { file(«/var/log/servers/$HOST/$YEAR/$MONTH/$DAY/user.log» owner(«root») group(«root») perm(0640) dir_perm(0750) create_dirs(yes)); }; destination r_uucp { file(«/var/log/servers/$HOST/$YEAR/$MONTH/$DAY/uucp.log» owner(«root») group(«root») perm(0640) dir_perm(0750) create_dirs(yes)); }; destination r_ppp { file(«/var/log/servers/$HOST/$YEAR/$MONTH/$DAY/ppp.log» owner(«root») group(«root») perm(0640) dir_perm(0750) create_dirs(yes)); }; destination r_mail { file(«/var/log/servers/$HOST/$YEAR/$MONTH/$DAY/mail.log» owner(«root») group(«root») perm(0640) dir_perm(0750) create_dirs(yes)); }; destination r_mailinfo { file(«/var/log/servers/$HOST/$YEAR/$MONTH/$DAY/mail.info» owner(«root») group(«root») perm(0640) dir_perm(0750) create_dirs(yes)); }; destination r_mailwarn { file(«/var/log/servers/$HOST/$YEAR/$MONTH/$DAY/mail.warn» owner(«root») group(«root») perm(0640) dir_perm(0750) create_dirs(yes)); }; destination r_mailerr { file(«/var/log/servers/$HOST/$YEAR/$MONTH/$DAY/mail.err» owner(«root») group(«root») perm(0640) dir_perm(0750) create_dirs(yes)); }; destination r_newscrit { file(«/var/log/servers/$HOST/$YEAR/$MONTH/$DAY/news.crit» owner(«root») group(«root») perm(0640) dir_perm(0750) create_dirs(yes)); }; destination r_newserr { file(«/var/log/servers/$HOST/$YEAR/$MONTH/$DAY/news.err» owner(«root») group(«root») perm(0640) dir_perm(0750) create_dirs(yes)); }; destination r_newsnotice { file(«/var/log/servers/$HOST/$YEAR/$MONTH/$DAY/news.notice» owner(«root») group(«root») perm(0640) dir_perm(0750) create_dirs(yes)); }; destination r_debug { file(«/var/log/servers/$HOST/$YEAR/$MONTH/$DAY/debug» owner(«root») group(«root») perm(0640) dir_perm(0750) create_dirs(yes)); }; destination r_messages { file(«/var/log/servers/$HOST/$YEAR/$MONTH/$DAY/messages» owner(«root») group(«root») perm(0640) dir_perm(0750) create_dirs(yes)); }; log { source(s_remote); filter(f_authpriv); destination(r_authlog); }; log { source(s_remote); filter(f_syslog); destination(r_syslog); }; log { source(s_remote); filter(f_cron); destination(r_cron); }; log { source(s_remote); filter(f_daemon); destination(r_daemon); }; log { source(s_remote); filter(f_kern); destination(r_kern); }; log { source(s_remote); filter(f_lpr); destination(r_lpr); }; log { source(s_remote); filter(f_mail); destination(r_mail); }; log { source(s_remote); filter(f_user); destination(r_user); }; log { source(s_remote); filter(f_uucp); destination(r_uucp); }; log { source(s_remote); filter(f_mail); filter(f_info); destination(r_mailinfo); }; log { source(s_remote); filter(f_mail); filter(f_warn); destination(r_mailwarn); }; log { source(s_remote); filter(f_mail); filter(f_err); destination(r_mailerr); }; log { source(s_remote); filter(f_news); filter(f_crit); destination(r_newscrit); }; log { source(s_remote); filter(f_news); filter(f_err); destination(r_newserr); }; log { source(s_remote); filter(f_news); filter(f_notice); destination(r_newsnotice); }; log { source(s_remote); filter(f_debug); destination(r_debug); }; log { source(s_remote); filter(f_messages); destination(r_messages); }; log { source(s_remote); filter(f_ppp); destination(r_ppp); };

2.

Принцип работы Syslog

Создайте каталог .

Запуск syslog-ng

1. Запустите службу syslog-ng:

# service syslog stop # service syslog-ng start

Первой командой вы отключили стандартную службу syslog.

2. Настройте автозапуск службы syslog-ng:

# chkconfig —level 0123456 syslog off # chkconfig —level 35 syslog-ng on

Заключение

Таким образом, нами был настроен полнофункциональный syslog-сервер syslog-ng для централизованного сбора данных от сетевого оборудования.

Автор: Денис Фролов

syslog(3) — Linux man page

2018-02-27 10:34:00 502 0

Настройка сервера Syslog-ng для сбора логов

Syslog-ng — это одно из самых популярных приложений для сбора логов на Unix-системах, которое является альтернативой для привычной для многих Syslog.

Установку будем производить на сервере с операционной системой Ubuntu-16.04

Устанавливаем сервер syslog-ng из репозиториев

sudo apt-get update

sudo apt-get install syslog-ng

При этом будет удален сервер логирования rsyslog, который установлен в системе по-умолчанию. И будет произведена начальная настройка syslog-ng.

Основной конфигурационный файл /etc/syslog-ng/syslog-ng.conf

После установки в нем уже будут настроены основные глодальные опции и ведение логов аналогично тому как их ведет сервер rsyslog по-умолчанию.

Новые записи желательно создавать в файлах в директорий /etc/syslog-ng/conf.d/, окончание файлов на *.conf

Разберемся с синтаксисом и параметрами, в syslog-ng они называеются глобльными объектами.

Sources(Источники) — Откуда syslog-ng получает лог-сообщения.

source «Индификатор» { «параметры»;};

  • «Индификатор» — произвольное имя, которое вы присвоите этому объекту;
  • «Параметры» — непосредственно указывается откуда будут получаться лог-сообщения(возможно указать несколько параметров).

Пример:

source s_tcp { tcp(ip(10.25.128.1) port(514)); };

Получение лог-сообщения, приходящие на ip адрес 10.25.128.1, на порт 514, по протоколу tcp.

Возможные значения параметров источников:

  • internal() — Сообщения, которые генерирует сам syslog-ng;
  • unix-stream() — Открыть указанный unix-сокет в SOCK_STREAM режиме и слушать входящие сообщения (unix-stream(«/dev/log»); };);
  • unix-dgram() — Открыть указанный unix-сокет в SOCK_DGRAM режиме и слушать входящие сообщения;
  • file() — Открыть указанный файл и прочитать сообщения из него;
  • pipe() — Открыть указанный pipe и прочитать сообщения из него;
  • tcp() — Слушать указанный TCP порт и указанном ip;
  • udp() — Слушать указанный UDP порт и указанном ip;
  • tcp6() — Слушать указанный TCP порт и указанном IPv6;
  • udp6() — Слушать указанный UDP порт и указанном IPv6;

Указанный источник может быть использован в нескольких различных log path.

Дляф этого к нему можно обращаться по индификатору. Указание нескольких источников с одинаковым индификаторм, может вызвать проблемы с работой сервера.

Destination(Насзначение) — куда будут отправляться лог-сообщения после обработки их сервером syslog-ng.

Так же состоит из «Индификатора» и «Параметров».

Пример:

destination d_file { file(«/var/log/test.log»);};

Записывать полученные лог-сообщения в файл «/var/log/test.log»

Возможные значения параметров:

  • file() — Записывать лог-сообщения в указанный файл;
  • fifo(),pipe() — Записывать лог-сообщения в указанный pipe;
  • program() — Запускать указанную программу и отправлять лог-сообщение к ней на вход;
  • sql() — Отправлять сообщение в базу данных. Доступно только в премиум релизе;
  • tcp() — Отправлять сообщение на по протоколу TCP на указанный удаленный хост (ip,port);
  • udp() — Отправлять сообщение на по протоколу UDP на указанный удаленный хост (ip,port);
  • tcp6() — Отправлять сообщение на по протоколу TCP на указанный удаленный хост по протокулу IPv6;
  • udp6() — Отправлять сообщение на по протоколу UDP на указанный удаленный хост по протокулу IPv6;
  • unix-stream() — Отправлять сообщения на указанный unix-сокет;
  • usertty() — Отправлять сообщения в терминал к указанному пользователю, если он залогирован в системе.

Template(Шаблоны) — Используются для определения вида записи лог-сообщений в том виде, который удобен пользователю

template temp_test { template(«$ISODATE — $HOST_FROM $MSG\n») };

Запись в виде «описание даты — «хост откуда пришло сообщение» «тело сообщения»

Основные макросы для шаблонов:

  • $ISODATE\$FULLDATE — варианты описания даты;
  • $FACILITY — каким facility сгенерированно сообщение (auth,cron,mail и т.д.);
  • $PRIORITY — уровень сообщения (info,err и т.д.);
  • $HOST — откуда пришло сообщение;
  • $HOST_FROM — последний хост в цепочке;
  • $PROGRAM — имя программы, которая сгенирировала сообщение;
  • $PID — pid процесса;
  • $MSG — тело сообщения.

Шаблоны записываются в объекты destination
Могут указываться в виде полного указания или в виде указания индификатора шаблона.

template temp_test { template(«$ISODATE — $HOST_FROM $MSG\n») }; destination d_file { file(«/var/log/test.log») template(temp_test)}; ИЛИ destination d_file { file(«/var/log/test.log») template(«$ISODATE — $HOST $MSG»)};

Log path() — Определяет что делать с входящим сообщением, на основании указанных фильтров.

log { source(s1); filter(f1); destination(d1); flags();};

Пример:

source s_tcp { tcp(ip(10.25.128.1) port(514)); }; destination d_file { file(«/var/log/test.log»);}; log { source(s_tcp); destination(d_file); flags(final); };

Читать лог-сообщения пришедшие по протоколу TCP на ip адрес 10.25.128.1 и порт 514 и записывать их в файл /var/log/test.log и логировать только в этот destination.

Filters(фильтры) — Используются для определения какие лог-сообщения и куда отправлять.

filter «Индификатор» { «Выражения» ;};

Пример:

filter test { host(«test.test.un») and match(«Kernel») ;};

Под фильтр попадет сообщение, которое будет содержать слово «Kernel» и прийдет от хоста test.test.un

В фильтрах с параметрами host(), match(), program() возможно исползование регулярных выражений. Параметры можно объединять между собой с помощью логических операторов and, or, not.

Основные выражения для фильтров:

  • facility() — под фильтр попадают сообщения с определенным facility;
  • host() — фильтрация по хосту отправителю;
  • level() or priority() — Фильтрация по уровню сообщения;
  • match() — фильтрация по совпадения в сообщении;
  • program() — фильтрация по имени программы, сгенерировавшей выражение.

Примеры:

source s_udp { udp(ip(0.0.0.0) port(514)); }; destination d_router { file(«/var/log/cisco_router.log»); }; destination d_radius { file(«/var/log/radius_server.log»); }; filter cisco_filter { host(192.168.0.1); }; filter auth_log { host(192.168.0.100) and match(«*auth*»); }; log { source(s_udp); filter(cisco_filter); destination(d_router); }; log { source(s_udp); filter(auth_log); destination(d_radius); };

Указываем в качестве источника все сообщения пришедшие по протоколу UDP на любой ip-адрес сервера на порт 514. Сообщения пришедшие с хоста с ip-адресом 192.168.0.1 записываем в файл «/var/log/cisco_router.log», а сообщения пришедшие с хоста с ip-адресом 192.168.0.100 и содержащие в теле сообщения словосочетание «auth», записываем в файл «/var/log/radius_server.log»

FILED UNDER : IT

Submit a Comment

Must be required * marked fields.

:*
:*