tmux logging complete output to a file

I’ve needed to log the complete output of a node.js process I’ve been running, even though I’ve been logging everything, there are some situations where the process completely crashes and nothing was logged.

To log the output of tmux you can use pipes, but in my case I wanted something simpler and more easier and flexible.

I’ve been using the command script to log the output to a file, so we can adjust our approach a little so we can log everything automatically.

In the ~/.bash_profile we need to append the following lines

if [[ $TERM = "screen" ]] && [[ $(ps -p $PPID -o comm=) = "tmux" ]]; then
mkdir $HOME/logs 2> /dev/null
logname="$(date '+%d%m%Y%H%M%S').tmux.log"
script -f $HOME/logs/${logname}

What this does is, when you start tmux manually it will output all the screen output to a log file, but this is always not sufficient.

In my case I was using tmux to start some commands from the shell with new-session, and this approach for some reason it doesn’t work.

So what I did is, I created a script that I will run to start everything I need

tmux new-session -s session -d -n "session" "bash"
tmux send -t session.0 ". $HOME/.bash_profile" ENTER
tmux send -t session.0 "<COMMAND 1 I NEED TO RUN>" ENTER
tmux send -t session.0 "<COMMAND 2 I NEED TO RUN>" ENTER
tmux send -t session.0 "<COMMAND 3 I NEED TO RUN>" ENTER
tmux send -t session.0 "<COMMAND n I NEED TO RUN>" ENTER

So what this does, it manually loads the .bash_profile script and we are good to go, we can log automatically again. This can also be used to load all the environments in tmux