Registro del sistema Linux: cd / var / log /
/ var / log / Hay un archivo de registro principal entre los varios archivos de registro a continuación: mensaje
En ubuntu16.04, el archivo de registro principal es syslog
-rw-r ----- 1 syslog adm 258172 22 de febrero 18:37 syslog
Servicio syslogd: todos los procesos que necesitan escribir registros del sistema envían sus propios registros del sistema al servicio syslogd
Entonces, ¿cómo envía los registros de su sistema al servicio syslogd? A través de la siguiente interfaz:
openlog()
syslog()
closelog()
La combinación de estas tres funciones imprimirá los registros necesarios en el archivo de registro principal, como / var / log / message
NAME
closelog, openlog, syslog, vsyslog - send messages to the system logger
SYNOPSIS
#include <syslog.h>
void openlog(const char *ident, int option, int facility);//参数 :名字 ,日志携带标志 ,记录消息的程序类型
void syslog(int priority, const char *format, ...);//参数: 日志级别 ,提交内容
void closelog(void);
openlog () abre una conexión al registrador del sistema para el programa. La cadena a la que apunta ident se coloca delante de cada mensaje y generalmente se establece como el nombre del programa. Si ident está vacío, se utiliza el nombre del programa. El parámetro de opción especifica las banderas que controlan la operación openlog () y las llamadas posteriores a syslog ()
syslog () genera un mensaje de registro, que se distribuye a través de syslogd (8). El parámetro de prioridad se forma sumando la herramienta y el valor de nivel (explicado más adelante). Los parámetros restantes son un formato, como
printf (3) y cualquier parámetro requerido por el formato, excepto la secuencia de dos caracteres% m, que será reemplazada por la cadena de mensaje de error strerror (errno). Si es necesario, puede agregar una nueva línea al final.
opción
The option argument to openlog() is an OR of any of these:
LOG_CONS Write directly to system console if there is an error while sending to system logger.
LOG_NDELAY Open the connection immediately (normally, the connection is opened when the first message is logged).
LOG_NOWAIT Don't wait for child processes that may have been created while logging the message. (The GNU C library does not create a child process, so this option has no effect on Linux.)
LOG_ODELAY The converse of LOG_NDELAY; opening of the connection is delayed until syslog() is called. (This is the default, and need not be specified.)
LOG_PERROR (Not in POSIX.1-2001 or POSIX.1-2008.) Print to stderr as well.
LOG_PID Include PID with each message.
instalaciones
El argumento de facilidad se usa para especificar qué tipo de programa está registrando el mensaje. Esto permite que el archivo de configuración especifique que los mensajes de diferentes instalaciones se manejarán de manera diferente.
LOG_AUTH security/authorization messages
LOG_AUTHPRIV security/authorization messages (private)
LOG_CRON clock daemon (cron and at)
LOG_DAEMON system daemons without separate facility value
LOG_FTP ftp daemon
LOG_KERN kernel messages (these can't be generated from user processes)
LOG_LOCAL0 through LOG_LOCAL7
reserved for local use
LOG_LPR line printer subsystem
LOG_MAIL mail subsystem
LOG_NEWS USENET news subsystem
LOG_SYSLOG messages generated internally by syslogd(8)
LOG_USER (default)
generic user-level messages
LOG_UUCP UUCP subsystem
nivel
Esto determina la importancia del mensaje. Los niveles son, en orden de importancia decreciente:
LOG_EMERG system is unusable
LOG_ALERT action must be taken immediately
LOG_CRIT critical conditions
LOG_ERR error conditions
LOG_WARNING warning conditions
LOG_NOTICE normal, but significant, condition
LOG_INFO informational message
LOG_DEBUG debug-level message
The function setlogmask(3) can be used to restrict logging to specified levels only.
Experimento: imprima el registro del sistema, modifique el experimento del proceso del demonio
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <syslog.h>
#define FILENAME "/tmp/out"
static int craetdeamon(void)
{
pid_t pid;
int fd;
pid = fork();
if(pid < 0)
{
perror("fork()");
return -1;
}
if(pid > 0)
{
printf("%d\n",getpid());
exit(0);
}
fd = open("/dev/null",O_RDWR);
if(fd < 0)
{
perror("open()");
return -1;
}
dup2(fd,0);
dup2(fd,1);
dup2(fd,2);
if(fd > 2)
{
close(fd);
}
setsid();
chdir("/");
return 0;
}
int main(int argc,char* argv[])
{
FILE* fp;
int i;
openlog("craetdeamon",LOG_PID,LOG_DAEMON);//与系统日志建立联系
if(craetdeamon())
{
syslog(LOG_ERR,"craetdeamon failed!");//上报
exit(1);
}else{
syslog(LOG_INFO,"craetdeamon successded!");
}
fp = fopen(FILENAME,"w");
if(fp == NULL)
{
syslog(LOG_ERR,"fopen %s failed!",FILENAME);
exit(1);
}
syslog(LOG_INFO,"fopen %s successede!",FILENAME);
for(i = 0; ;i++)
{
fprintf(fp,"%d\n",i);
fflush(fp);
syslog(LOG_DEBUG,"%d is printed!",i);
sleep(1);
}
exit(0);
}
Ver / var / log / syslog con privilegios de root para ver la salida del archivo de registro del sistema