- Linux samba log level
- Наши партнеры
- Using Samba
- 4.8 Logging Configuration Options
- 4.8.1 Using syslog
- 4.8.2 Logging Configuration Options
- Configuring Logging on a Samba Server
- Namespaces
- Page actions
- Contents
- Introduction
- Setting the Log File Name
- Setting the Maximum Log File Size
- Setting the Log Level
- Setting a Universal Log Level
- Setting Individual Log Levels for Debug Classes
- Логирование операций с файлами в Samba
- Введение
- Включаем логирование операций в samba
- Вывод лога доступа к файлам samba в отдельный файл
- Заключение
- Linux samba log level
Linux samba log level
Наши партнеры
Библиотека сайта rus-linux.net
|
Using Samba
4.8 Logging Configuration Options
Occasionally, we need to find out what Samba is up to. This is especially true when Samba is performing an unexpected action or is not performing at all. To find out this information, we need to check Samba’s log files to see exactly why it did what it did.
Samba log files can be as brief or verbose as you like. Here is an example of what a Samba log file looks like:
Many of these options are of use only to Samba programmers. However, we will go over the meaning of some of these entries in more detail in Chapter 9, Troubleshooting Samba .
Samba contains six options that allow users to describe how and where logging information should be written. Each of these options are global options and cannot appear inside a share definition. Here is an up-to-date configuration file that covers each of the share and logging options that we’ve seen so far:
Here, we’ve added a custom log file that reports information up to debug level 2. This is a relatively light debugging level. The logging level ranges from 1 to 10, where level 1 provides only a small amount of information and level 10 provides a plethora of low-level information. Level 2 will provide us with useful debugging information without wasting disk space on our server. In practice, you should avoid using log levels greater than 3 unless you are programming Samba.
This file is located in the /var/log directory thanks to the log file configuration option. However, we can use variable substitution to create log files specifically for individual users or clients, such as with the %m variable in the following line:
Isolating the log messages can be invaluable in tracking down a network error if you know the problem is coming from a specific machine or user.
We’ve added another precaution to the log files: no one log file can exceed 50 kilobytes in size, as specified by the max log size option. If a log file exceeds this size, the contents are moved to a file with the same name but with the suffix .old appended. If the .old file already exists, it is overwritten and its contents are lost. The original file is cleared, waiting to receive new logging information. This prevents the hard drive from being overwhelmed with Samba log files during the life of our daemons.
For convenience, we have decided to leave the debug timestamp in the logs with the debug timestamp option, which is the default behavior. This will place a timestamp next to each message in the logging file. If we were not interested in this information, we could specify no for this option instead.
4.8.1 Using syslog
If you wish to use the system logger ( syslog) in addition to or in place of the standard Samba logging file, Samba provides options for this as well. However, to use syslog, the first thing you will have to do is make sure that Samba was built with the configure —with-syslog option. See Chapter 2 for more information on configuring and compiling Samba.
Once that is done, you will need to configure your /etc/syslog.conf to accept logging information from Samba. If there is not already a daemon.* entry in the /etc/syslog.conf file, add the following:
This specifies that any logging information from system daemons will be stored in the /var/log/daemon.log file. This is where the Samba information will be stored as well. From there, you can specify the following global option in your configuration file:
This specifies that any logging messages with a level of 1 will be sent to both the syslog and the Samba logging files. (The mappings to syslog priorities are described in the upcoming section «syslog.») Let’s assume that we set the regular log level option above to 4. Any logging messages with a level of 2, 3, or 4 will be sent to the Samba logging files, but not to the syslog. Only level 1 logging messages will be sent to both. If the syslog value exceeds the log level value, nothing will be written to the syslog.
If you want to specify that messages be sent only to syslog — and not to the standard Samba logging files — you can place this option in the configuration file:
If this is the case, any logging information above the number specified in the syslog option will be discarded, just like the log level option.
4.8.2 Logging Configuration Options
Table 4.7 lists each of the logging configuration options that Samba can use.
Источник
Configuring Logging on a Samba Server
Namespaces
Page actions
Contents
Introduction
On a Samba server you can use logging to write detailed log files to find and debug problems, or to monitor events, such as users connecting to a share. Setting a log level enable you to control the amount of data that is logged. Additionally, you can use debug classes you to set individual log levels for certain events, such as authentication or Winbind-related events, while logging all other events on a different level.
Setting the Log File Name
Samba logs events to the file set in the log file parameter. You can either set this parameter to one static file name to log all events to one file, or you can use variables to create individual log files. For example, to create log files for each connecting host named NetBIOS_name.log in the /var/log/samba/ folder:
- Set the log file parameter in the [global] section in the smb.conf :
For further details, see:
- log file parameter description in the smb.conf (5) man page
- VARIABLE SUBSTITUTIONS section in the smb.conf (5) man page
- Reload Samba:
Setting the Maximum Log File Size
To control the maximum size of Samba log files, set the max log size parameter. The parameter takes the value in KB. If the size exceeds the value set, Samba appends .old to the log file name and writes new log entries to a new file.
During the log file is rotated, Samba overrides a previously archived version of the log file. |
To set the maximum log size to 10 MB:
- Set the max log size parameter in the [global] section in the smb.conf to 10000 :
- Reload Samba:
Setting the Log Level
Using the default settings, logging is disabled. To enable logging, set the log level parameter in the [global] section in the smb.conf .
A higher log level includes logging of events from lower levels. |
Setting a Universal Log Level
In most scenarios you set set one log level for all events. For example, to set the log level to 1 (lowest level were Samba writes log entries):
- Set the log level parameter in the [global] section in the smb.conf to 1 :
- Reload Samba:
Setting Individual Log Levels for Debug Classes
In certain situations, for example, to debug authentication problems, you need to set a higher log level. However, setting a higher log level causes Samba to log all events on the higher level, what can result in large log files. Samba enables you to set individual log levels for certain debug classes, while logging all other events on a different level.
For example, to set the default log level to 1 and log authentication and Winbind-related events on log level 5 :
Источник
Логирование операций с файлами в Samba
Ранее я неоднократно рассказывал, как настроить файловый сервер samba для совместной работы с файлами. При совместной работе часто бывает нужно знать, кто и когда что-то сделал с тем или иным файлом, а конкретно, кто удалил файл. По-умолчанию, такой лог не ведется, нужно настраивать отдельно. Займемся настройкой логирования операций с файлами в данной статье.
Введение
У меня есть две статьи по настройке файлового сервера samba:
В обоих случаях будет не лишним настроить логирование всех обращений к файлам на сервере. Делается это штатными возможностями самой самбы. Она будет отправлять логи в syslog, а в нем мы уже настроим их хранение и ротацию с помощью logrotate. На нагруженных серверах логи будут очень объемными. Нужно обязательно позаботиться об их хранении и удалении.
Я буду настраивать логи в samba на сервере CentOS 7. В других случаях отличий почти не будет. Сами настройки самбы везде одинаковые. Syslog и Logrotate тоже примерно одинаковые во всех дистрибутивах Linux.
Включаем логирование операций в samba
Для логирования действий пользователей на файловом сервере будем использовать модуль самбы full_audit. Если вы хотите выполнять логирование операций с файлами в один лог файл по всем доступным шарам, то добавляйте настройки аудита в глобальную секцию. Если же захотите разделить по шарам, то отдельно в каждую шару с небольшими изменениями. Я рассмотрю оба варианта. Для начала, настроим аудит по всем шарам в один общий файл. Добавляем в /etc/samba/smb.conf в секцию [global] следующие строки:
Поясню каждый параметр.
full_audit:prefix | В каком формате будет выводиться информация о подключении: %u — имя пользователя, %I — его ip адрес, %S — название шары. |
full_audit:success | Какие удачные события будут логироваться. В приведенном примере по смыслу и так понятно, о чем речь. Полный список событий такой: chdir, chflags, chmod, chmod_acl, chown, close, closedir, connect, disconnect, disk_free, fchmod, fchmod_acl, fchown, fget_nt_acl, fgetxattr, flistxattr, fremovexattr, fset_nt_acl, fsetxattr, fstat, fsync, ftruncate, get_nt_acl, get_quota, get_shadow_copy_data, getlock, getwd, getxattr, kernel_flock, link, linux_setlease, listxattr, lock, lseek, lstat, mkdir, mknod, open, opendir, pread, pwrite, read, readdir, readlink, realpath, removexattr, rename, rewinddir, rmdir, seekdir, sendfile, set_nt_acl, set_quota, setxattr, stat, statvfs, symlink, sys_acl_delete_def_file, sys_acl_get_fd, sys_acl_get_file, sys_acl_set_fd, sys_acl_set_file, telldir, unlink, utime, write. |
full_audit:failure | То же самое, что выше, только для ошибок. |
full_audit:facility | Категория событий syslog, в которую будут попадать записи. |
full_audit:priority | Приоритет записей для syslog. Для самбы будет достаточно приоритета notice, чем ее записи по сути и являются. |
Если вы хотите настроить вывод лога доступа с разных шар в отдельные файлы, то указанные выше параметры поместите не в глобальную, а отдельно в каждую секцию с шарой, изменив категории событий, сделав их в каждой шаре уникальными, например local5 и local6. Так же нужно будет в каждую шару отдельно добавить еще один параметр:
После изменения конфигурации, не забудьте перезапустить самбу. Если больше ничего не делать, то логи посещений самбы польются в стандартный поток вывода для системных логов. В Centos в /var/log/messages. Это очень неудобно, поэтому далее настроим вывод логов в отдельный файл.
Вывод лога доступа к файлам samba в отдельный файл
Нам нужно отредактировать файл конфигурации rsyslog для направления вывода лога самбы в отдельный файл. В CentOS 7 открываем файл /etc/rsyslog.conf и добавляем в самый конец такую строку:
Этим параметром мы направили вывод логов аудита посещений в отдельный файл audit.log. Если все оставить как есть, то информация о посещениях будет писаться как в отдельный файл, так и в общий системный. Чтобы в общий не писалось, редактируем еще одну строку, добавляя туда выделенный фрагмент:
Сохраняем файл и перезапускаем rsyslog.
Теперь все нормально. Все логи посещений шары на samba будут складываться в отдельный файл и только туда. Если у вас есть желание хранить логи на удаленном сервере, то воспользуйтесь моей статье на эту тему — настройка syslog-ng для удаленного сбора логов. Это сделать быстро и просто. Зачастую это может быть оправданно и удобно, особенно с точки зрения безопасности и не только логов от самбы.
Осталось малось — настроить ротацию логов. Сделать это надо обязательно, так как файл аудита будет расти очень быстро. Здесь ничего особенного, используем logrotate. Скорее всего у вас уже есть фал конфигурации logrotate для самбы. Он создается в момент установки. Отредактируем его, добавив новые параметры.
Я храню логи за последние 90 дней, ротацию делаю раз в день и складываю старые логи в отдельную папку. Если у вас в конфигурации есть параметр с маской, который захватывает сразу все файлы в директории /var/log/samba, например вот так:
То либо вынесите лог-файл с аудитом в отдельную директорию, либо измените маску.
Заключение
Я уже давно заметил один неприятный баг в самбе 4-й версии. Привожу пример того, как выглядит лог посещений файловой шары самбы с русскими названиями в именах на 3 и 4-й версии. В данном случае сначала версия 3.6.3, потом 4.6.2
В первом случае отображаются полные корректные пути. Во втором случае на события типа open идут только обрывки названий директорий, по которым не понятен полный путь. Делаю важный акцент — только на события open. Если идут события создания, удаления, изменения, то пути уже корректны, даже если они русские. В принципе, события на доступ лично для меня обычно не важны. Интерес представляет только создание, изменение и особенно удаление файлов. С этим все в порядке. Аудит показывает корректный лог удаления файлов. Но все равно не приятно смотреть на неинформативный лог.
Возможно, дело не в 3-1 и 4-й версии. Я не проверял различные изменения в рамках одной и той же ветки. Просто посмотрел на имеющиеся у меня сервера. Там где 3-я версия все в порядке, там где 4-я везде такой бардак в логах. Если кто-то знает, как от него избавиться, прошу поделиться.
Источник
Linux samba log level
Occasionally, we need to find out what Samba is up to. This is especially true when Samba is performing an unexpected action or is not performing at all. To find out this information, we need to check Samba’s log files to see exactly why it did what it did.
Samba log files can be as brief or verbose as you like. Here is an example of what a Samba log file looks like:
Many of these options are of use only to Samba programmers. However, we will go over the meaning of some of these entries in more detail in Chapter 9, Troubleshooting Samba .
Samba contains six options that allow users to describe how and where logging information should be written. Each of these options are global options and cannot appear inside a share definition. Here is an up-to-date configuration file that covers each of the share and logging options that we’ve seen so far:
Here, we’ve added a custom log file that reports information up to debug level 2. This is a relatively light debugging level. The logging level ranges from 1 to 10, where level 1 provides only a small amount of information and level 10 provides a plethora of low-level information. Level 2 will provide us with useful debugging information without wasting disk space on our server. In practice, you should avoid using log levels greater than 3 unless you are programming Samba.
This file is located in the /var/log directory thanks to the log file configuration option. However, we can use variable substitution to create log files specifically for individual users or clients, such as with the %m variable in the following line:
Isolating the log messages can be invaluable in tracking down a network error if you know the problem is coming from a specific machine or user.
We’ve added another precaution to the log files: no one log file can exceed 50 kilobytes in size, as specified by the max log size option. If a log file exceeds this size, the contents are moved to a file with the same name but with the suffix .old appended. If the .old file already exists, it is overwritten and its contents are lost. The original file is cleared, waiting to receive new logging information. This prevents the hard drive from being overwhelmed with Samba log files during the life of our daemons.
For convenience, we have decided to leave the debug timestamp in the logs with the debug timestamp option, which is the default behavior. This will place a timestamp next to each message in the logging file. If we were not interested in this information, we could specify no for this option instead.
If you wish to use the system logger ( syslog ) in addition to or in place of the standard Samba logging file, Samba provides options for this as well. However, to use syslog, the first thing you will have to do is make sure that Samba was built with the configure —with-syslog option. See Chapter 2 for more information on configuring and compiling Samba.
Once that is done, you will need to configure your /etc/syslog.conf to accept logging information from Samba. If there is not already a daemon.* entry in the /etc/syslog.conf file, add the following:
This specifies that any logging information from system daemons will be stored in the /var/log/daemon.log file. This is where the Samba information will be stored as well. From there, you can specify the following global option in your configuration file:
This specifies that any logging messages with a level of 1 will be sent to both the syslog and the Samba logging files. (The mappings to syslog priorities are described in the upcoming section «syslog.») Let’s assume that we set the regular log level option above to 4. Any logging messages with a level of 2, 3, or 4 will be sent to the Samba logging files, but not to the syslog. Only level 1 logging messages will be sent to both. If the syslog value exceeds the log level value, nothing will be written to the syslog.
If you want to specify that messages be sent only to syslog — and not to the standard Samba logging files — you can place this option in the configuration file:
If this is the case, any logging information above the number specified in the syslog option will be discarded, just like the log level option.
Table 4.7 lists each of the logging configuration options that Samba can use.
Источник