# Log rotation

When creating a MongoDB instance using the DMK (`dmk_dbcreate.py`), log rotation should be setup to ensure logs are managed effectively.

#### DMK Log Directory Structure

As part of the instance creation process, DMK generates the log directory:

```
/u04/mongodb/log/<instance_name>
```

A symbolic link is also created from:

```
/u01/app/mongodb/admin/<instance_name>/log -> /u04/mongodb/log/<instance_name>
```

This keeps logs in a centralized volume and separates them from binary, data, and backup paths.

#### Log Configuration in the MongoDB Template

The log rotation behavior is controlled via the MongoDB configuration file, which is generated from the template provided in the DMK YAML:

```yaml
systemLog:
  destination: file
  path: ${log_path}/${instance_name}.log
  logAppend: true
```

To support external rotation using tools like `logrotate`, the following line should be present:

```yaml
  logRotate: reopen
```

This instructs MongoDB to reopen its log file when receiving a `SIGUSR1` signal, making external rotation seamless.

{% hint style="info" %}
Starting with **release 2.3.0** of the DMK, this is the default configuration when creating a MongoDB instance with DMK.
{% endhint %}

#### System Log Rotation with logrotate

DMK recommends a `logrotate` configuration, typically found in:

```
/etc/logrotate.d/mongodb
```

The template `logrotate` configuration look like this :

{% code title="${DMK\_HOME}/templates/etc/mongo\_logrotate.template" overflow="wrap" %}

```conf

MONGO_LOGFILE {
    daily
    rotate 7
    maxage 7
    missingok
    compress
    delaycompress
    copytruncate
    create 644 mongodb mongodb
    sharedscripts
    postrotate
        # Notify the specific MongoDB instance after rotation
        systemctl kill --signal=SIGUSR1 mongod_INSTANCE_NAME 2>/dev/null || true
    endscript
}

```

{% endcode %}

This configuration ensures:

* Daily rotation
* 7 archived logs kept
* Compression of older logs
* No error if the log file is missing
* No rotation of empty files

#### Manual Log Rotation

You can also trigger log rotation manually, from the shell:

```bash
kill -SIGUSR1 <mongod_pid>
```

#### Further Reading

* [Creating a MongoDB Instance](https://dbi-services.gitbook.io/dmk-mongodb/managing-databases/creating_mongo_instance)
