> For the complete documentation index, see [llms.txt](https://book.bsdcn.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://book.bsdcn.org/ask/flat/chapter-17-system-administration/di-17.6-jie-xi-tong-ri-zhi-guan-li.md).

# 17.6 System Log Management

This section covers FreeBSD system log management.

## Configuring Local Logging

The configuration file **/etc/syslog.conf** defines how syslogd handles log entries when they are received. This file controls logging behavior through two parameters: **facility** and **level**:

* **Facility** identifies the subsystem from which the message originates (such as the kernel or a daemon).
* **Level** indicates the severity of the event.

You can determine where log messages are recorded based on **facility** and **level**, and you can also filter log messages by the application that sent them. In remote logging, you can also filter by the hostname that generated the log event.

Each line in this configuration file defines one action, consisting of a selector field and an action field.

* The selector field syntax is **facility.level**, matching log messages from the **facility** with a level of **level** or higher.
  * An optional comparison flag can also be added before the level to more precisely specify what to log.
  * Multiple selector fields can be used for the same action
    * Separated by semicolons (`;`).
    * Use \* to match everything.
* The action field specifies the destination for log messages, such as a file or a remote log host.

The following is an example of FreeBSD's default **/etc/syslog.conf** file, whose source file is **usr.sbin/syslogd/syslog.conf**:

```ini
#
#	Spaces ARE valid field separators in this file. However,
#	other *nix-like systems still insist on using tabs as field
#	separators. If you are sharing this file between systems, you
#	may want to use only tabs as field separators here.
#	Consult the syslog.conf(5) manpage.
*.err;kern.warning;auth.notice;mail.crit		/dev/console # ①
*.notice;authpriv.none;kern.debug;lpr.info;mail.crit;news.err	/var/log/messages
security.*					/var/log/security
auth.info;authpriv.info				/var/log/auth.log
mail.info					/var/log/maillog # ②
cron.*						/var/log/cron
!-devd
*.=debug					/var/log/debug.log # ③
*.emerg						*
daemon.info					/var/log/daemon.log
# uncomment this to log all writes to /dev/console to /var/log/console.log
# touch /var/log/console.log and chmod it to mode 600 before it will work
#console.info					/var/log/console.log
# uncomment this to enable logging of all log messages to /var/log/all.log
# touch /var/log/all.log and chmod it to mode 600 before it will work
#*.*						/var/log/all.log
# uncomment this to enable logging to a remote loghost named loghost
#*.*						@loghost
# uncomment these if you're running inn
# news.crit					/var/log/news/news.crit
# news.err					/var/log/news/news.err
# news.notice					/var/log/news/news.notice
# Uncomment this if you wish to see messages produced by devd
# !devd
# *.>=notice					/var/log/devd.log # ④
!*
include						/etc/syslog.d
include						/usr/local/etc/syslog.d
```

* ① Matches all messages with a level of `err` or higher, as well as `kern.warning`, `auth.notice`, and `mail.crit`, and sends these log messages to the console (**/dev/console**).

  ```sh
  # ls -al /dev/console
  crw-------  1 root wheel 0x8 May 16 10:09 /dev/console
  ```
* ② Matches all messages from the `mail` subsystem with a level of `info` or higher, and logs them to the **/var/log/maillog** file.
* ③ Uses the comparison flag (`=`) to match only messages with a level of `debug`, and logs them to the **/var/log/debug.log** file.
* ④ This example demonstrates the use of program-specific specification: subsequent rules only apply to the specified program. In this case, only messages generated by devd(8) are logged to the **/var/log/devd.log** file.

## Logging Facilities

A facility identifies the subsystem that generates messages, used to separate messages from different sources for easier log review.

**Table: syslog Facilities**

| Name                  | Description                                                                                                      |
| --------------------- | ---------------------------------------------------------------------------------------------------------------- |
| auth                  | Authorization system: login(1), su(1), getty(8), etc.                                                            |
| authpriv              | Same as auth, but logged to files readable only by root.                                                         |
| console               | Messages written to **/dev/console** by the kernel console output driver.                                        |
| cron                  | Messages written by the cron(8) daemon.                                                                          |
| daemon                | System daemons, such as routed(8), that do not have a dedicated logging facility.                                |
| ftp                   | FTP daemon.                                                                                                      |
| kern                  | Messages generated by the kernel. These messages cannot be generated by any user process.                        |
| lpr                   | Printer spooling system: lpr(1), lpc(8), lpd(8), etc.                                                            |
| mail                  | Mail system.                                                                                                     |
| mark                  | This facility adds one record every 20 minutes.                                                                  |
| news                  | Network news system.                                                                                             |
| ntp                   | Network Time Protocol system.                                                                                    |
| security              | Security subsystem, such as ipfw(4).                                                                             |
| syslog                | Messages generated internally by syslogd(8).                                                                     |
| user                  | Messages generated by random user processes. **This is the default facility identifier when none is specified**. |
| uucp                  | UUCP subsystem.                                                                                                  |
| local0 through local7 | Reserved for local use.                                                                                          |

## Logging Levels

A level indicates the severity of a message. The following is a list of keywords ordered from highest to lowest priority:

**Table: syslog Levels**

| Name    | Description                                                                        |
| ------- | ---------------------------------------------------------------------------------- |
| emerg   | Emergency condition. Typically broadcast to all users.                             |
| alert   | Condition that must be corrected immediately, such as a corrupted system database. |
| crit    | Critical condition, such as a hardware device error.                               |
| err     | Error.                                                                             |
| warning | Warning message.                                                                   |
| notice  | Non-error condition, but one that may require special handling.                    |
| info    | Informational message.                                                             |
| debug   | Message useful only when debugging a program.                                      |
| none    | This special level disables a specific facility.                                   |

## Reading Log Messages

FreeBSD's syslogd(8) supports two output formats, switchable via the `-O` option:

* **BSD/RFC 3164 format** (default format, `-O bsd` or `-O rfc3164`): Traditional BSD syslog format.
* **Syslog/RFC 5424 format** (`-O syslog` or `-O rfc5424`): A newer standard format using [RFC 3339](https://datatracker.ietf.org/doc/html/rfc3339) timestamps (with microsecond precision), and including structured facility and severity fields in each message.

**RFC 3164 format** logs typically use the following syntax:

```ini
date time hostname program[processID]: message
```

The following is an output example from the **/var/log/cron** file:

```ini
[other output omitted]
May 15 15:30:00 ykla /usr/sbin/cron[1812]: (root) CMD (/usr/libexec/atrun)
May 15 15:33:00 ykla /usr/sbin/cron[1814]: (operator) CMD (/usr/libexec/save-entropy)
[other output omitted]
```

You can enable verbose logging in syslogd(8) by running the following command, which will append the facility and level to each message:

```sh
# sysrc syslogd_flags="-vv"
```

After enabling this feature, the facility and level will be displayed in the logs, as shown below:

```ini
[other output omitted]
May 17 18:55:00 <cron.info> ykla /usr/sbin/cron[1771]: (operator) CMD (/usr/libexec/save-entropy)
May 17 18:55:00 <cron.info> ykla /usr/sbin/cron[1772]: (root) CMD (/usr/libexec/atrun)
[other output omitted]
```

To switch to RFC 5424 format, you can configure it in the **/etc/rc.conf** file:

```sh
# sysrc syslogd_flags="-O syslog"
```

The following is an output example from the **/var/log/cron** file in RFC 5424 format:

```sh
<78>1 2026-05-17T19:00:00.004642+08:00 ykla /usr/sbin/cron 1781 - - (root) CMD (newsyslog)
<78>1 2026-05-17T19:00:00.011902+08:00 ykla /usr/sbin/cron 1783 - - (operator) CMD (/usr/libexec/save-entropy)
<78>1 2026-05-17T19:00:00.017709+08:00 ykla /usr/sbin/cron 1785 - - (root) CMD (/usr/libexec/atrun)
```

RFC 5424 format enables verbose logging by default without requiring the `-vv` option.

```sh
<priority>version timestamp hostname program[processID] messageID [structured-data] log-message
```

## Log Management and Rotation

Log files grow rapidly, consuming disk space and making it harder to find useful information. To address this, FreeBSD uses newsyslog(8) to manage log files.

newsyslog periodically rotates and compresses log files, optionally creates missing log files, and signals programs when log files are moved. The default configuration source file for newsyslog is **usr.sbin/newsyslog/newsyslog.conf**.

```ini
# configuration file for newsyslog
#
# Entries which do not specify the '/pid_file' field will cause the
# syslogd process to be signalled when that log file is rotated.  This
# action is only appropriate for log files which are written to by the
# syslogd process (ie, files listed in /etc/syslog.conf).  If there
# is no process which needs to be signalled when a given log file is
# rotated, then the entry for that file should include the 'N' flag.
#
# Note: some sites will want to select more restrictive protections than the
# defaults.  In particular, it may be desirable to switch many of the 644
# entries to 640 or 600.  For example, some sites will consider the
# contents of maillog, messages, and lpd-errs to be confidential.  In the
# future, these defaults may change to more conservative ones.
#
# logfilename          [owner:group]    mode count size when  flags [/pid_file] [sig_num]
/var/log/all.log			600  7	   *	@T00  J
/var/log/auth.log			600  7	   1000 @0101T JC
/var/log/console.log			600  5	   1000	*     J
/var/log/cron				600  3	   1000	*     JC
/var/log/daemon.log			644  5	   1000	@0101T JC
/var/log/daily.log			640  7	   *	@T00  JN
/var/log/debug.log			600  7	   1000 *     JC
/var/log/devd.log			644  3	   1000	*     JC
/var/log/init.log			644  3	   1000	*     J
/var/log/kerberos.log			600  7	   1000	*     J
/var/log/maillog			640  7	   *	@T00  JC
/var/log/messages			644  5	   1000	@0101T JC
/var/log/monthly.log			640  12	   *	$M1D0 JN
/var/log/security			600  10	   1000	*     JC
/var/log/utx.log			644  3	   *	@01T05 B
/var/log/weekly.log			640  5	   *	$W6D0 JN

<include> /etc/newsyslog.conf.d/[!.]*.conf
<include> /usr/local/etc/newsyslog.conf.d/[!.]*.conf
```

Field descriptions:

* `logfilename` - The name of the system log file to be archived.
* `[owner:group]` - Specifies the owner and group of the archive file.
* `mode` - Specifies the file mode for the log file and archive files. Valid mode bits are 0666, meaning read/write permissions for owner, group, and others can be specified for archived logs.
* `count` - Specifies the maximum number of archive files that can exist.
* `size` - When the log file reaches the specified size (in KB), the log file will be rotated. If this field contains an asterisk (\*), rotation is not based on size.
* `when` - Contains a time interval, a specific time, or both.
* `flags` - Indicates the flags accepted by newsyslog.
* `[/pid_file]` - Specifies the filename containing the daemon's process ID, or for looking up group process IDs.
* `[sig_num]` - Specifies the signal number to be sent to the daemon when rotating files.

> **Tip**
>
> The last two fields `[/pid_file]` and `[sig_num]` are optional, specifying the PID filename of the process and the signal number to send to the process when rotating files.

### Manually Rotating Logs

Although newsyslog(8) is invoked hourly by cron(8) by default, you can also manually trigger rotation using the `-F` option:

```sh
# newsyslog -F
```

Force rotation of all log files that meet the criteria. The rotated files will look like the following:

```sh
/var/log/auth.log          /var/log/devd.log          /var/log/ppp.log
/var/log/auth.log.0.bz2    /var/log/devd.log.0.bz2    /var/log/ppp.log.0.bz2
```

To rotate a specific file, specify the file path:

```sh
# newsyslog -F /var/log/auth.log
```

The rotation result is as follows:

```sh
auth.log.0.bz2
auth.log
auth.log.1.bz2
```

## Configuring Remote Logging

As the number of systems increases, monitoring log files across multiple hosts adds management overhead. Configuring centralized logging can reduce this burden.

In FreeBSD, you can use syslogd and newsyslog to configure centralized log file aggregation, merging, and rotation.

In the example configuration for this section, host `A` (**192.168.5.18**) acts as the log client, named `logclient.example.com`.

Host `A` will pass log information to log server `B`.

### Setting Up DNS Resolution

The log server and all client hosts must have forward and reverse entries in the local DNS. If the network does not have a DNS server, create entries in the **/etc/hosts** file on each system. Name resolution must be correct to ensure that log entries are not rejected by the log server.

Add the following two lines to the **/etc/hosts** file on both log client `A` and log server `B`:

```ini
192.168.5.18            logclient.example.com
192.168.5.17            logserv.example.com
```

> **Tip**
>
> The **192.168.5.18**, **192.168.5.17**, `logclient.example.com`, and `logserv.example.com` in the above examples are placeholders and must be replaced with actual values.

Host `B` serves as the log server (**192.168.5.17**), named `logserv.example.com`, and will collect log information from the local network.

### Log Client Configuration

The log client sends log entries to the log server on the network. The client also retains its own copy of the logs.

On log client A, execute the following command to enable syslogd at startup:

```sh
# service syslogd enable
```

Prevent this client from receiving logs from other hosts (`-s`), while increasing the verbosity of log messages:

```sh
# sysrc syslogd_flags="-s -v -v"
```

After that, define the log server in the client's **/etc/syslog.conf** file. In this example, all logged facilities are sent to the specified host using the `@` symbol:

```sh
*.*  @logserv.example.com
```

After saving the edits, restart syslogd for the changes to take effect:

```sh
# service syslogd restart
```

### Log Server Configuration

A log server is a system configured to accept log information from other hosts.

After configuring log client A, on log server B, edit the **/etc/syslog.conf** file:

```ini
+logclient.example.com
*.*     /var/log/logclient.log
```

In the above example, the log client's hostname is added as a filter condition in the log server's configuration. All log entries from all facilities and levels from host **logclient.example.com** are stored uniformly in the server's local **/var/log/logclient.log** file.

You can add multiple log clients by adding similar two-line entries for each client.

Execute the following command to enable syslogd at startup:

```sh
# service syslogd enable
```

Allow log entries from the specified client:

```sh
# sysrc syslogd_flags="-a logclient.example.com -v -v"
```

* `-v -v` increases the verbosity of log messages, helping administrators see the types of messages recorded under each facility.
* To allow logging from multiple clients, you can specify multiple `-a` options. You can also specify IP addresses and entire network segments.

Finally, create the log file **logclient.log**:

```sh
# touch /var/log/logclient.log
```

At this point, restart syslogd and verify:

```sh
# service syslogd restart
# pgrep syslogd
```

If a PID is returned, the server has been successfully restarted.

```sh
1958
1961
1962
```

If the server fails to restart, check the **/var/log/messages** file for error information.

To test whether log messages are being sent over the network, you can use logger(1) on the client to send a message to syslogd:

```sh
# logger "Test Message by logclient."
```

This message should appear in both the client's **/var/log/messages** file and the log server's **/var/log/logclient.log** file.

```sh
May 17 21:58:08 <user.notice> logclient ykla[1881]: Test Message by logclient.
```

### Debugging the Log Server

If there is a firewall between the log server and the log client, ensure that the firewall ruleset allows UDP port 514 traffic between the client and server.

```sh
# nc -uvz logserv.example.com 514
Connection to logserv.example.com 514 port [udp/syslog] succeeded!
```

```sh
# nc -uvz logclient.example.com 514
Connection to logclient.example.com 514 port [udp/syslog] succeeded!
```

If the log server is not receiving any messages, the cause is typically network connectivity issues, hostname resolution problems, or typos in the configuration file. To troubleshoot, ensure that the log server and log client can `ping` each other using the hostnames specified in the **/etc/rc.conf** file. If this fails, check network cabling, firewall rulesets, and the DNS server or hostname entries in **/etc/hosts** on both the log server and client. Repeat the checks until the `ping` test succeeds.

If `ping` succeeds on both hosts but the server still does not receive log messages, you can temporarily increase log verbosity to narrow down the configuration issue. In the following example, **/var/log/logclient.log** on the log server is empty, and **/var/log/messages** on the log client does not show the reason for the failure.

To increase debug output, edit the `syslogd_flags` entry on the log server and execute a restart:

```sh
# sysrc syslogd_flags="-d -a logclient.example.com -v -v"
```

> **Warning** Please try using IP addresses instead of domain names for testing first.
>
> After debugging is successful, you must revert to the original settings, otherwise it will affect normal system boot.

```sh
# service syslogd restart
```

After restarting, debug data will be immediately output to the console, similar to the following:

```sh
……partial output omitted……

logmsg: pri 56, flags 0, from logserv, msg restart
syslogd: restarted
logmsg: pri 6, flags 0, from logserv, msg kernel boot file is /boot/kernel/kernel
kernel boot file is /boot/kernel/kernel
received sa_len = 16
cvthname(2) len = 16
cvthname(192.168.5.18)
validate: dgram from IP 192.168.5.18, port 514, name logclient.example.com;
accepted in rule 1.
logmsg: pri 15, flags 0, from logclient, msg Test Message by logclient.
Logging to FILE /var/log/logclient.log
Logging to FILE /var/log/messages
```

At this point, messages are being correctly received and written to the correct file.

### Security Considerations

As with all network services, security requirements should be considered before implementing a log server. Log files may contain sensitive information about services enabled on the local host, user accounts, and configuration data.

**Network Security**:

Network data sent from the client to the server is not encrypted or password-protected. If encrypted transmission is required, consider the following options:

* Use **security/stunnel** to create an SSL-encrypted tunnel for syslog data transmission.
* Deploy the log server in a trusted internal network, with firewall restrictions on access.

**Receiver Security**:

Receiving log messages via UDP is equivalent to an "unauthenticated remote disk-filling service." Therefore:

* It is strongly recommended to use the `-a` option to explicitly limit the hosts allowed to send logs, rather than accepting logs from all sources.
* If remote log reception is not needed, use the `-s` parameter to enable secure mode. Specifying `-ss` twice will completely disable network sockets.
* You can restrict the access sources for UDP port 514 on the firewall.

**Local Security**:

Log files are not encrypted during use or after log rotation. Local users may gain additional information about system configuration by accessing log files. Therefore, setting appropriate permissions on log files is essential. newsyslog supports setting permissions for newly created and rotated log files. Setting log files (such as `auth.log`) to mode `600` prevents unauthorized access by local users.

## References

* FreeBSD Project. syslog.conf(5)\[EB/OL]. \[2025-05-17]. <https://man.freebsd.org/cgi/man.cgi?query=syslog.conf&sektion=5>. syslog configuration file manual page.
* FreeBSD Project. syslogd(8)\[EB/OL]. \[2025-05-17]. <https://man.freebsd.org/cgi/man.cgi?query=syslogd&sektion=8>. syslog daemon manual page.
* FreeBSD Project. newsyslog.conf(5)\[EB/OL]. \[2025-05-17]. <https://man.freebsd.org/cgi/man.cgi?query=newsyslog.conf&sektion=5>. newsyslog configuration file manual page.
* FreeBSD Project. logger(1)\[EB/OL]. \[2025-05-17]. <https://man.freebsd.org/cgi/man.cgi?query=logger&sektion=1>. Command-line log sending tool manual page.

## Exercises

1. Configure `syslog.conf` to log all `auth` facility messages separately to the **/var/log/auth.log** file.
2. Modify the `newsyslog.conf` configuration to increase the number of retained backups for **/var/log/messages** from 5 to 10.
3. Use the `grep` command to search for recent failed SSH login attempt records.
4. Manually trigger `newsyslog` to rotate the `/var/log/auth.log` file and observe the rotation results.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://book.bsdcn.org/ask/flat/chapter-17-system-administration/di-17.6-jie-xi-tong-ri-zhi-guan-li.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
