Add to log file linux

Write to custom log file from a Bash script

In Linux, I know how to write a simply message to the /var/log/messages file, in a simple shell script I created:

I want to stop throwing messages into the default /var/log/messages file, and create my own. I tried this:

#!/bin/bash logger "have more fun" > /var/log/mycustomlog 

It still logs to /var/log/messages . It did create the /var/log/mycustomlog , but it’s empty. Anyone see what I’m missing?

Redirecting standard output doesn’t work because logger doesn’t write to standard output; it writes to the file configured by syslog(3) to receive log messages.

5 Answers 5

logger logs to syslog facilities. If you want the message to go to a particular file you have to modify the syslog configuration accordingly. You could add a line like this:

and restart syslog. Then you can log like this:

logger -p local7.info "information message" logger -p local7.err "error message" 

and the messages will appear in the desired logfile with the correct log level.

Without making changes to the syslog configuration you could use logger like this:

logger -s "foo bar" >> /var/log/mycustomlog 

That would instruct logger to print the message to STDERR as well (in addition to logging it to syslog), so you could redirect STDERR to a file. However, it would be utterly pointless, because the message is already logged via syslog anyway (with the default priority user.notice ).

For anyone else who was confused at the use of the number 2 after the string in the last example, 1 redirects stdout, and 2 redirects stderr. More info available here: tldp.org/LDP/abs/html/io-redirection.html

And for anyone who doesn’t know how to edit the syslog configuration, here it is on Ubuntu: askubuntu.com/questions/42152/where-is-syslog-conf

What does the — before the file path indicate? I’ve tried googling around but can’t find anything about it. Is it required?

@chepner make a good point that logger is dedicated to logging messages.

I do need to mention that @Thomas Haratyk simply inquired why I didn’t simply use echo .

At the time, I didn’t know about echo, as I’m learning shell-scripting , but he was right.

My simple solution is now this:

#!/bin/bash echo "This logs to where I want, but using echo" > /var/log/mycustomlog 

The example above will overwrite the file after the >

So, I can append to that file with this:

#!/bin/bash echo "I will just append to my custom log file" >> /var/log/customlog 
  • on a side note, it’s simply my personal preference to keep my personal logs in /var/log/ , but I’m sure there are other good ideas out there. And since I didn’t create a daemon, /var/log/ probably isn’t the best place for my custom log file. (just saying)
Читайте также:  Orange pi android linux

I agree that this is a good approach but the log file will keep growing and there is no mechanism of archiving or deleting old logs. If you log frequently, then this can take considerable amount of storage.

There’s good amount of detail on logging for shell scripts via global varaibles of shell. We can emulate the similar kind of logging in shell script: http://www.cubicrace.com/2016/03/efficient-logging-mechnism-in-shell.html The post has details on introdducing log levels like INFO , DEBUG, ERROR. Tracing details like script entry, script exit, function entry, function exit.

If you see the man page of logger:

LOGGER(1) BSD General Commands Manual LOGGER(1)

NAME logger — a shell command interface to the syslog(3) system log module

SYNOPSIS logger [-isd] [-f file] [-p pri] [-t tag] [-u socket] [message . ]

DESCRIPTION Logger makes entries in the system log. It provides a shell command interface to the syslog(3) system log module.

It Clearly says that it will log to system log. If you want to log to file, you can use «>>» to redirect to log file.

This is an incorrect interpretation of the man page. logger uses syslog or (in the case of most Linux systems) rsyslog which can be configured to place log messages where ever you like.

I did it by using a filter. Most linux systems use rsyslog these days. The config files are located at /etc/rsyslog.conf and /etc/rsyslog.d .

Whenever I run the command logger -t SRI some message , I want «some message» to only show up in /var/log/sri.log .

To do this I added the file /etc/rsyslog.d/00-sri.conf with the following content.

# Filter all messages whose tag starts with SRI # Note that 'isequal, "SRI:"' or 'isequal "SRI"' will not work. # :syslogtag, startswith, "SRI" /var/log/sri.log # The stop command prevents this message from getting processed any further. # Thus the message will not show up in /var/log/messages. # & stop 

Then restart the rsyslogd service:

systemctl restart rsyslog.service 

Here is a shell session showing the results:

[root@rpm-server html]# logger -t SRI Hello World! [root@rpm-server html]# cat /var/log/sri.log Jun 5 10:33:01 rpm-server SRI[11785]: Hello World! [root@rpm-server html]# [root@rpm-server html]# # see that nothing shows up in /var/log/messages [root@rpm-server html]# tail -10 /var/log/messages | grep SRI [root@rpm-server html]# 

Источник

Use the Logger command to add to the Linux Log file

Use the logger command to add messages to the Linux system log file. The logger command is part of the util Linux package, so do not install it. Here are some examples:

Читайте также:  Adobe illustrator linux alternative

1.1. Simple use

$ logger Welcome to OSTechNix $logger "Welcome to OSTechNix blog"

The above command adds the entry «Welcome to OSTechNix» to the system log file.
Let’s use the «tail» command to verify that the message has been added:

Jan 31 07:19:23 ubuntuserver systemd[1705]: Listening on REST API socket Jan 31 07:33:14 ubuntuserver sk: Welcome to OSTechNix

be careful:
Different Linux operating systems store log messages in different files. I recommend that you check the / var/log / directory to see which files the logs are stored in. On RPM based systems such as CentOS, regular log messages are stored in the / var/log/messages file instead of the / var/log/syslog file.

1.2. Common parameters

logger is used to write logs to the system. It provides a shell command interface to the syslog system module
Syntax:

-d, --udp Using datagrams(UDP)Instead of using the default stream connection(TCP) -i, --id Record each time line by line logger Process of ID -f, --file file_name Record specific files -h, --help Display help text and exit -n, --server Write to the specified remote syslog Server, using UDP Replace built-in syslog Routine for -P, --port port_num Use specified UDP Port. The default port number is 514 -p, --priority priority_level Specifies the priority of the input message, which can be numeric or specified as " facility.level" Format. For example:" -p local3.info " local3 The message level of this device is info. The default level is "user.notice" -s, --stderr Output standard errors to the system log. -t, --tag tag Specify tag record -u, --socket socket Write the specified socket,Instead of going to the built-in system log routine. -V, --version Real version information and exit
facility: auth: User authorization authpriv: Authorization and security cron: Planning tasks daemon: System daemon kern: Kernel related information lpr Information about print services mail Email related information news Information from news server syslog from syslog Generated information user Information generated by the user's program, default uucp from uucp Generated information local0~7 Used to define local policies level: alert Immediate action is required crit Critical state debug debugging emerg System unavailable err Error status error Error status info Normal message notice Normal, but pay attention
$ logger -i 'Howdy, Welcome to OSTechNix blog'

Verify log messages using the tail command:

$ tail -l /var/log/syslog [. ] Jul 1 10:23:22 10-23-97-171 ubuntu[18813]: Howdy, Welcome to OSTechNix blog

18813 is the process ID of the logger.

Add labels to messages
You may notice in the output above that the newly added entry is marked with the currently logged in user name (i.e. sk). The default label is the name of the user logged in on the terminal. However, we can use the — t flag to record each line as a record with a specific tag.

$ logger -i -t ostechnix 'Howdy, Welcome to OSTechNix blog' Check log entries: $ tail -l /var/log/syslog [. ] Jan 31 07:54:02 ubuntuserver ostechnix[1881]: Howdy, Welcome to OSTechNix blog

The last entry has the ostechnix tag and its process ID is 1881.

Читайте также:  Количество строк кода ядра linux

Add message from file to log file
You can also add entries in the file to our system log file.

Let’s create a sample text file.

$ echo "This is test file" > file.txt $ cat file.txt This is test file

Now, use the following command to save the file Txt to the system log file:

$ logger -f file.txt $ tail -l /var/log/syslog [. ] Jan 31 08:43:06 ubuntuserver sk: This is test file

If there are any blank lines in the input file, you can exclude them from being added to the log file using the — e flag as shown below

Priority record message
Messages can be logged with a given priority.

$ logger "Welcome To OSTechNix" --priority user.warning

The default priority is «user.notice». Refer to the logger man page for all available priority options.

Send input and messages from «stdin» to the system log
We can use the command to enter content from the rack input, and then use the following command to push it into the system log:

$ echo "Welcome to OSTechNix" | logger

The logger sends messages to the remote log server
To send a message to a remote syslog server running on a specific port, run:

$ logger "Welcome to OSTechNix" --server --port Or, $ logger "Welcome to OSTechNix" -n -p The default port number is 514.

Limit message size
We can use the – size flag to set the maximum message size allowed.

$ logger --size 5 abcdefghijklmnopqrswxyz View log message size: $ tail -l /var/log/syslog [. ] Jan 31 09:09:02 ubuntuserver sk: abcde The default value is 1 KiB Character.

Posted by THEMADGEEK on Sat, 22 Jan 2022 22:07:26 +1030

  • Java — 5996
  • Python — 2604
  • Algorithm — 1737
  • Javascript — 1708
  • Back-end — 1577
  • Front-end — 1561
  • Linux — 1389
  • C++ — 1378
  • data structure — 1135
  • Database — 953
  • Spring — 922
  • C — 836
  • MySQL — 835
  • Android — 683
  • Spring Boot — 660
  • Vue.js — 549
  • Design Pattern — 543
  • Operation & Maintenance — 509
  • Deep Learning — 487
  • Interview — 459

Источник

Оцените статью
Adblock
detector