The selected answer doesn't work quite well with multiple sessions and doesn't allow to specify a custom log file name.
For multiple screen sessions, this is my formula:
Create a configuration file for each process:
logfile test.log
logfile flush 1
log on
logtstamp after 1
logtstamp string "[ %t: %Y-%m-%d %c:%s ]\012"
logtstamp on
If you want to do it "on the fly", you can change logfile
automatically.
\012
means "new line", as using \n
will print it on the log file: source.
Start your command with the "-c" and "-L" flags:
screen -c ./test.conf -dmSL 'Test' ./test.pl
That's it. You will see "test.log" after the first flush:
...
6 Something is happening...
[ test.pl: 2016-06-01 13:02:53 ]
7 Something else...
[ test.pl: 2016-06-01 13:02:54 ]
8 Nothing here
[ test.pl: 2016-06-01 13:02:55 ]
9 Something is happening...
[ test.pl: 2016-06-01 13:02:56 ]
10 Something else...
[ test.pl: 2016-06-01 13:02:57 ]
11 Nothing here
[ test.pl: 2016-06-01 13:02:58 ]
...
I found that "-L" is still required even when "log on" is on the configuration file.
I couldn't find a list of the time format variables (like %m) used by screen. If you have a link of those formats, please post it bellow.
In case you want to do it "on the fly", you can use this script:
#!/bin/bash
if [[ $2 == "" ]]; then
echo "Usage: $0 name command";
exit 1;
fi
name=$1
command=$2
path="/var/log";
config="logfile ${path}/${name}.log
logfile flush 1
log on
logtstamp after 1
logtstamp string \"[ %t: %Y-%m-%d %c:%s ]\012\"
logtstamp on";
echo "$config" > /tmp/log.conf
screen -c /tmp/log.conf -dmSL "$name" $command
rm /tmp/log.conf
To use it, save it (screen.sh) and set +x permissions:
./screen.sh TEST ./test.pl
... and will execute ./test.pl and create a log file in /var/log/TEST.log