logger: add support for -I PID to log, e.g., $$ from a shell script

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
This commit is contained in:
Joachim Wiberg 2022-07-31 12:03:57 +02:00
parent f32ca837c1
commit 4f94756bf2
4 changed files with 26 additions and 3 deletions

View File

@ -38,6 +38,7 @@
.Op Fl f Ar FILE
.Op Fl h Ar HOST
.Op Fl H Ar HOSTNAME
.Op Fl I Ar PID
.Op Fl m Ar MSGID
.Op Fl p Ar PRIO
.Op Fl P Ar PORT
@ -105,6 +106,16 @@ will be used.
Send the message to the remote system
.Ar host
instead of logging it locally.
.It Fl I Ar PID
Like
.Fl i ,
but uses
.Ar PID .
Useful when logging from shell scripts that send multiple messages.
E.g., the following arguments might be a useful template:
.Bd -literal -offset indent
logger -t $(basename $0) -I $$
.Ed
.It Fl i
Log the process id of the logger process with each line
.Ql ( LOG_PID ) .

View File

@ -238,6 +238,7 @@ static int usage(int code)
" -h HOST Send (UDP) message to this remote syslog server (IP or DNS name)\n"
" -H NAME Use NAME instead of system hostname in message header\n"
" -i Log process ID of the logger process with each line (LOG_PID)\n"
" -I PID Log process ID using PID, recommed using PID $$ for shell scripts\n"
#ifdef __linux__
" -k Log to kernel /dev/kmsg if /dev/log doesn't exist yet\n"
#endif
@ -278,7 +279,7 @@ int main(int argc, char *argv[])
int c, num = 5;
int rotate = 0;
while ((c = getopt(argc, argv, "46?bcd:f:h:H:ikm:np:P:r:st:u:v")) != EOF) {
while ((c = getopt(argc, argv, "46?bcd:f:h:H:iI:km:np:P:r:st:u:v")) != EOF) {
switch (c) {
case '4':
family = AF_INET;
@ -316,6 +317,11 @@ int main(int argc, char *argv[])
log_opts |= LOG_PID;
break;
case 'I':
log_opts |= LOG_PID;
log.log_pid = atoi(optarg);
break;
case 'k':
#ifdef __linux__
allow_kmsg = 1;

View File

@ -299,7 +299,9 @@ vsyslogp_r(int pri, struct syslog_data *data, const char *msgid,
DEC();
if (data->log_stat & LOG_PID) {
prlen = snprintf(p, tbuf_left, "[%d]", getpid());
if (data->log_pid == -1)
data->log_pid = getpid();
prlen = snprintf(p, tbuf_left, "[%d]", data->log_pid);
DEC();
}
strlcat(p, ":", tbuf_left);
@ -368,7 +370,9 @@ vsyslogp_r(int pri, struct syslog_data *data, const char *msgid,
DEC();
if (data->log_stat & LOG_PID) {
prlen = snprintf(p, tbuf_left, "%d ", getpid());
if (data->log_pid == -1)
data->log_pid = getpid();
prlen = snprintf(p, tbuf_left, "%d ", data->log_pid);
if (data->log_stat & (LOG_PERROR|LOG_CONS|LOG_NLOG)) {
iov[iovcnt].iov_base = __UNCONST("[");
iov[iovcnt].iov_len = 1;

View File

@ -208,6 +208,7 @@ struct syslog_data {
int log_fac;
int log_mask;
void *log_host; /* struct sockaddr* */
int log_pid;
};
#define SYSLOG_DATA_INIT { \
@ -222,6 +223,7 @@ struct syslog_data {
.log_fac = LOG_USER, \
.log_mask = 0xff, \
.log_host = NULL, \
.log_pid = -1, \
}
#ifdef __cplusplus