50

How can I write an entry into /var/log/syslog from the command line?

Drew Noakes
  • 5,628
  • 5
  • 41
  • 55

3 Answers3

59

Use the logger command.

logger Some message to write

There are several options available, including:

-i Log the process ID in each line
-f Log the contents of a specified file
-n Write to the specified remote syslog server
-p Specify a priority
-t Tag the line with a specified tag

See man 1 logger for more information on the tool.

Drew Noakes
  • 5,628
  • 5
  • 41
  • 55
  • 1
    For a more detailed `logger` example, and for remote logging via `netcat` or shell redirection, see: https://www.safaribooksonline.com/library/view/bash-cookbook/0596526784/ch15s14.html –  Jan 16 '18 at 15:19
14

Alternatively, you can write to syslog from python:

python -c 'import syslog; syslog.syslog("Hello World")'
Sylvain Pineau
  • 61,564
  • 18
  • 149
  • 183
  • 3
    Honest question: what would be the benefits of using Python for this over the `logger` command? – Drew Noakes Oct 30 '14 at 11:44
  • 2
    @DrewNoakes If you're running a - python - script from the command line, using the standard library is always better than relying on subprocess and call `logger`. You already have my vote, I'm just mentioning an alternative. – Sylvain Pineau Oct 30 '14 at 11:51
  • Thanks for the clarification. I guess this is true for all programming languages. Have a vote on me. – Drew Noakes Oct 30 '14 at 11:54
  • just a thought - loading a heavy environment to log something to a file is not as ideal as using a simple tool like logger, especially if you want want to script it. – pdwalker Apr 13 '21 at 15:44
4

As a dev, I rarely have time to closely study man pages, so TLDR:

logger -p local0.notice -t ${0##*/}[$$] Hello world

The gibberish in the middle will translate to the calling program. So if you check the bottom of syslog you'll see something like:

May 07 08:27:14 ip-10-1-11-166 -bash[42108]: Hello world
DarkNeuron
  • 302
  • 1
  • 3
  • 9