A quick bash function to automate logging on Dashcam

In the world of software development, logging is an essential practice. Dashcam relies heavily in logging the output of your apps! Whether you’re debugging an application or monitoring its performance, having access to log files can be a lifesaver. Dashcam augments your logs by adding video to them!

Today, we’re going to explore a simple yet powerful bash function that allows you to quickly save application output to a file. Here’s the function:

dash() {
  2>&1 | tee -a "${1:-dashcam.log}"
}

Copy paste the above code into your .bashrc file if you’re on Linux (on my Macbook M2 you need to paste it inside.zshrc instead).

These files are available in your $HOME directory. To quickly edit this file simply point an editor of your choice like this:

nano ~/.zshrc 
  • N.B. Replace ~/.zshrc to ~/.bashrc if you’re not on a Mac or at least be aware that on your OS it might be different

Paste and then save by hitting CTRL+X and saving the file

Last but not least, you want to restart your Terminal app or open a new window which will cause the .zshrc file to be re-read and the function you just wrote parsed.

How Does It Work?

This function utilizes the tee command (we talked about it in this blogpost), which reads from standard input and writes to standard output and files. The -a flag ensures that the output is appended to the file rather than overwriting it.

The "${1:-dashcam.log}" part of the command checks if a filename has been provided as an argument ($1). If not, it defaults to "dashcam.log".

Basic usage

Imagine you’re running an npm command such as npm run dev and you want to capture the output of that command in a log file so that Dashcam can then use it. This is how I would run it:

npm run dev dash

By default this writes the file in the current directory!

If you wanted to save it to a different directory or filename you can do

npm run dev dash /tmp/some_file.log

Why Use dash function in bash?

For me, it is because I did not want to type & remember the whole syntax of the tee command

  • Simplicity: With just a single line of code, you can log the output of any command.
  • Flexibility: You can specify a filename or use the default.
  • Efficiency: Quickly save logs without disrupting your workflow.

One more thing

This bash function does not automate adding the log file to Dashcam. You still have to add the file as a pattern by following the instructions here

Conclusion

The dash function is a handy tool for developers, system administrators, or anyone who frequently works with log files and uses Dashcam.

By adding this function to your toolkit, you can streamline your logging process and keep essential information at your fingertips.

Give it a try, and you’ll find that sometimes, the simplest solutions can be the most powerful!

Leave a Reply

%d bloggers like this: