Home > Software engineering >  How to create a symlink to point to latest rotating log file
How to create a symlink to point to latest rotating log file

Time:06-06

I've my application log file which keeps rotating and it has a pattern like below postgresql-yyyy-mm-dd_hhmmss.log

-rw-------. 1 root root    331 Jun  1 22:04 postgresql-2022-06-01_220333.log.gz
-rw-------. 1 root root    417 Jun  1 22:04 postgresql-2022-06-01_220430.log.gz
-rw-------. 1 root root    289 Jun  2 19:28 postgresql-2022-06-02_000000.log.gz
-rw-------. 1 root root  26802 Jun  2 19:50 postgresql-2022-06-02_192809.log.gz
-rw-------. 1 root root   8440 Jun  2 23:57 postgresql-2022-06-02_195044.log.gz
-rw-------. 1 root root  15016 Jun  3 11:22 postgresql-2022-06-03_000000.log.gz
-rw-------. 1 root root    291 Jun  3 11:24 postgresql-2022-06-03_112405.log.gz
-rw-------. 1 root root    336 Jun  3 11:25 postgresql-2022-06-03_112553.log.gz
-rw-------. 1 root root    397 Jun  3 11:27 postgresql-2022-06-03_112714.log.gz
-rw-------. 1 root root    358 Jun  3 11:29 postgresql-2022-06-03_112901.log.gz
-rw-------. 1 root root    493 Jun  3 11:30 postgresql-2022-06-03_113031.log.gz
-rw-------. 1 root root    418 Jun  3 11:34 postgresql-2022-06-03_113354.log.gz
-rw-------. 1 root root    419 Jun  3 11:39 postgresql-2022-06-03_113920.log.gz
-rw-------. 1 root root    416 Jun  3 11:44 postgresql-2022-06-03_114437.log.gz
-rw-------. 1 root root    417 Jun  3 11:49 postgresql-2022-06-03_114943.log.gz
-rw-------. 1 root root    419 Jun  3 11:55 postgresql-2022-06-03_115530.log.gz
-rw-------. 1 root root  16961 Jun  3 23:56 postgresql-2022-06-03_120047.log.gz
-rw-------. 1 root root  35470 Jun  4 23:56 postgresql-2022-06-04_000000.log.gz
-rw-------. 1 root root 406059 Jun  5 17:56 postgresql-2022-06-05_000000.log

I want to run a small script(unix/linux) such that it creates a symlink in this folder which always points to the latest(current) logfile automatically for e.g

postgres.LOG -> postgresql-2022-06-05_000000.log

This way I don't have to ls and find out what is the current log file before opening, instead just open postgres.LOG.

CodePudding user response:

All rotated logfiles seem gzipped so the glob postgresql-*.log will expand to the logfile of interest:

ln -sf postgresql-*.log postgres.LOG

CodePudding user response:

The format of the filename makes sure that the newest file sorts as last using ls. So this should work:

ln -sf $(ls postgresql-*.log | tail -1) postgres.LOG 

CodePudding user response:

If you want the symbolic link to be changed automatically each time a new log file is created you need inotify.

Something like this

#! /bin/bash

log_dir=/your/log/dir
inotifywait -m -e create "$log_dir" | while read -r _dir event file
do
    if [[ ! -h "$log_dir/$file" && "$file" =~ \.log$ ]]
    then
        ln -sf "$log_dir/$file" "$log_dir/postgres.LOG"
    fi
done
  • Related