Many applications need to record their activities. System programs often need to write messages to the console or log files. These messages may indicate errors, warnings, or general information related to the system status. For example, the su program records the fact that a user tries to obtain the superuser permission but fails.
These logs are usually recorded in system files, and these system files are stored in directories dedicated to this purpose. It may be the/usr/ADM or/var/log directory. For a typical Linux installation, the file/var/log/messages contains all system information, And/var/log/mail contains other log information from the mail system, /var/log/debug may include debugging information. You can check the system configuration by viewing the/etc/syslog. conf file.
The following is an example of some log information:
Here, we can see various types of information recorded. The first few are the information reported by the Linux kernel when it starts and detects installed hardware. Then the Job Schedule Program cron reports that it is starting. Finally, the su Program reported that user Neil was granted the superuser permission.
You may need the superuser privilege to view log information.
Some UNIX systems do not provide readable log files as above, but provide administrators with tools to read the database of system events. For more information, see the system documentation.
Although the format and storage methods of system messages are different, the methods for generating messages are standard. The UNIX standard provides an interface for all programs to generate log information through the syslog function:
The SYSLOG function sends a log message to the system's log tool. Each piece of information has a priority parameter, which is a bitwise OR of a severity level and a facility value. The severity level controls the processing of log information, and the facility value records the source of log information.
The facility values defined in the header file syslog. h include log_user (default) -- it indicates that the message comes from a user application, and log_local0, log_local1 until log_local7. Their meanings are specified by the local administrator.
Severity levels are listed in descending order of priority, as shown in Table 4-6.
Table 4-6
Advanced
Description
Log_emerg
Emergency
Log_alert
High-priority faults, such as database crashes
Log_crit
Severe errors, such as hardware faults
Log_err
Error
Log_warning
Warning
Log_notice
Special situations that require attention
Log_info
General information
Log_debug
Debugging information
According to the system configuration, log_emerg information may be broadcast to all users, log_alert information may be emailed to the Administrator, log_debug information may be ignored, and other information may be written to the log file. To use the logging function, you only need to call the syslog function when you want to create a log.
The log information created by Syslog contains the message header and message body. The message consumption header is created based on the facility value, date, and time. The message body is created based on the Message Parameter of syslog. The function of this parameter is similar to the format string in printf. The number of other parameters of syslog depends on the printf type control converter in the message string. In addition, the control conversion character % m can be used to insert an error message string corresponding to the current value of the error variable errno. This is useful for logging error messages.
Experiment: syslog Function
In this program, we try to open a non-existent file:
Compile and run the program syslog. C. We didn't see the output, but the/var/log/messages file now has the following line at the end:
Feb 8 09:59:14 beast syslog: Oops-no such file or directory
Experiment Analysis
In this program, we try to open a non-existent file. After the file fails to be opened, we call syslog to record this event in system logs.
Note: The log information does not indicate which program calls the log function. It only records the fact that syslog is called to record a piece of information. The % m conversion control operator is replaced with an error description. In this example, "the file is not found ". This is more useful than reporting only one original error code.
The SYSLOG. h header file also defines some other functions that can change the behavior of log records. They are:
We can call the openlog function to change the log information representation. It allows us to set a string Ident, which is added before the log information. We can use it to specify which program has created this information. The facility parameter records a facility value, which serves as the default facility value for subsequent syslog calls. The default value is log_user. The logopt parameter is used to configure the behavior of subsequent syslog calls. It is a bitwise OR of 0 or multiple 4-7 values.
Table 4-7
Logopt Parameters
Description
Log_pid
The log information contains the process identifier, which is a unique value assigned to each process by the system.
Log_cons
If the information cannot be recorded in log files, send them to the console
Log_odelay
Enable the log function only when syslog is called for the first time.
Log_ndelay
Enable the log function immediately, instead of waiting for the first log record
The openlog function will allocate and open a file descriptor and use it to write logs. You can use the closelog function to close it. Note that you do not need to call openlog before calling syslog, because syslog will enable the log function as needed.
You can use the setlogmask function to set a log mask and control the priority of log information. Subsequent syslog calls whose priority is not set in the log mask will be discarded. For example, you can use this method to disable the log_debug message without changing the program body.
We can use log_mask (priority) to create a mask for log information, which is used to create a mask that only contains one priority. We can also use log_upto (priority) to create a mask consisting of all priorities (including specified priorities) before the specified priority.
Experiment: logmask Program
In this example, we will see the log mask function:
The logmask. C program has no output, but in a typical Linux system, the following information is displayed at the end of the/var/log/messages file:
Feb 8 10:00:50 beast logmask [1833]: informative message, pid = 1833
The file that receives debugging log information (usually/var/log/debug, or sometimes/var/log/messages) will contain the following information:
Feb 8 10:00:50 beast logmask [1833]: Debug message, shocould appear
Experiment Analysis
This program uses its own name logmask to initialize log functions and requires that the log information contain the process identifier. The general information is recorded in the file/var/log/messages, and the debugging information is recorded in the file/var/log/debug. The second debugging information does not appear, because we call setlogmask to ignore all information with a lower priority than log_notice (note that this approach may not be supported in earlier linux kernels ).
If your Linux installation version does not enable the debugging information logging function or uses other configurations, you may not be able to see the debugging information. To enable all debugging information, add the following line to/etc/syslog. the end of the conf file and restart the system (you can also send a pending signal to the syslogd process ). However, in any case, it is best to carefully check your system documentation to understand the correct format of the configuration file.
*. Debug/var/log/debug
Logmask. c uses the getpid function, which is closely related to its getppid function definition as follows:
The two functions return the process identifier (PID) of the parent process of the calling process and the calling process respectively ).
Use the syslog () function to process log information
Function declaration:
# Include <syslog. h>
Void syslog (INT priority, const char * message, arguments ...);
Format of the Priority parameter (severity level | Facility Code)
Example:
Log_err | log_user
Severity Level:
Priority Level description
Log_emerg an emergency situation
Log_alert high-priority problem, such as database resume uption
Log_crit critical error, such as hardware failure
Log_err errors
Log_warning warning
Log_notice special conditions requiring attention
Log_info informational messages
Log_debug debug messages
Facility value (converted from the syslog. h header file ):
/* Facility codes */
# Define log_kern (0 <3)/* kernel messages */
# Define log_user (1 <3)/* random user-level messages */
# Define log_mail (2 <3)/* Mail System */
# Define log_daemon (3 <3)/* system daemons */
# Define log_auth (4 <3)/* Security/authorization messages */
# Define log_syslog (5 <3)/* messages generated internally by syslogd */
# Define log_lpr (6 <3)/* Line Printer subsystem */
# Define log_news (7 <3)/* Network News subsystem */
# Define log_uucp (8 <3)/* uucp subsystem */
# Define log_cron (9 <3)/* Clock daemon */
# Define log_authpriv (10 <3)/* Security/authorization messages (private )*/
# Define log_ftp (11 <3)/* FTP daemon */
Sample Code:
# Include <syslog. h>
# Include <stdio. h>
Int main (void)
{
File * F;
F = fopen ("ABC", "R ");
If (! F)
Syslog (log_err | log_user, "test-% M/N ");
}
The above log information is automatically provided by the system. We can also filter the log information. The following functions are used:
# Include <syslog. h>
Void closelog (void );
Void openlog (const char * Ident, int logopt, int facility );
Int setlogmask (INT maskpri );
Logopt Parameter options:
Logopt parameter description
Log_pid identifier des the process identifier, a unique number allocated to each process by the system, in the messages.
Log_cons sends messages to the console if they can't be logged.
Log_odelay opens the Log facility at first call.
Log_ndelay opens the Log facility immediately, rather than at first log.
Sample Code:
# Include <syslog. h>
# Include <stdio. h>
# Include <unistd. h>
Int main (void)
{
Int logmask;
Openlog ("logmask", log_pid | log_cons, log_user);/* the log information contains the process ID. */
Syslog (log_info, "informative message, pid = % d", getpid ());
Syslog (log_debug, "Debug message, shocould appear");/* records the log information. */
Logmask = setlogmask (log_upto (log_notice);/* sets to shield log information lower than the notice level. */
Syslog (log_debug, "Debug message, shocould not appear");/* the log information is blocked and not recorded. */
}
Which file is stored in the/var/log directory for different security levels is/etc/syslog. the conf file is controlled. below is the syslog in my system. CONF file content:
#/Etc/syslog. conf configuration file for syslogd.
#
# For more information see syslog. conf (5)
# Manpage.
#
# First some standard logfiles. log by facility.
#
Auth, authpriv. */var/log/auth. Log
*. *; Auth, authpriv. None-/var/log/syslog
# Cron. */var/log/cron. Log
Daemon. *-/var/log/daemon. Log
Kern. *-/var/log/Kern. Log
LPR. *-/var/log/lpr. Log
Mail. *-/var/log/mail. Log
User. *-/var/log/user. Log
Uucp. */var/log/uucp. Log
#
# Logging for the mail system. Split it up so that
# It is easy to write scripts to parse these files.
#
Mail.info-/var/log/mail.info
Mail. Warn-/var/log/mail. Warn
Mail. Err/var/log/mail. Err
# Logging for INN news system
#
News. crit/var/log/news. crit
News. Err/var/log/news. Err
News. Notice-/var/log/news. Notice
#
# Some 'catch-all' logfiles.
#
*. = Debug ;/
Auth, authpriv. None ;/
News. None; mail. None-/var/log/debug
*. = Info; *. = notice; *. = warn ;/
Auth, authpriv. None ;/
Cron, daemon. None ;/
Mail, news. None-/var/log/messages
#
# Emergencies are sent to everybody logged in.
#
*. Emerg *
#
# I like to have messages displayed on the console, but only on a virtual
# Console I usually leave idle.
#
# Daemon, mail .*;/
# News. = crit; news. = err; news. = notice ;/
# *. = Debug; *. = Info ;/
# *. = Notice; *. = warn/dev/tty8
# The named pipe/dev/xconsole is for the 'xconsole' utility. To use it,
# You must invoke 'xconsole' with the '-file' option:
#
# $ Xconsole-file/dev/xconsole [...]
#
# Note: Adjust the list below, or you'll go crazy if you have a reasonably
# Busy site ..
#
Daemon. *; mail .*;/
News. crit; news. Err; news. Notice ;/
*. = Debug; *. = Info ;/
*. = Notice; *. = warn |/dev/xconsole
Instance code:
1 # include <string>
2 # include <iostream>
3 # include <algorithm>
4 # include <list>
5 # include <syslog. h>
6 using namespace STD;
7
8 // ============================================== ============
9
10 class tlog
11 {
12 public:
13 tlog ();
14 ~ Tlog ();
15 tlog & operator <(const char * P );
16 tlog & operator <(string & S );
17 tlog & operator <(tlog & (* pfun) (tlog &));
18
19 void debug (const char * P );
20 void debug (string & S );
21
22 void log (const char * P );
23 void log (string & S );
24 };
25 tlog & Endl (tlog & object );
26
27 const char * log_prefix = "root_log :";
28
29 tlog glog;
30
31 tlog: tlog ()
32 {
33 # ifdef log_syslogd
34 openlog (log_prefix, log_pid, log_user );
35 # endif
36}
37 tlog ::~ Tlog ()
38 {
39 # ifdef log_syslogd
40 closelog ();
41 # endif
42}
43
44 tlog & tlog: Operator <(const char * P)
45 {
46 # ifdef log_stdout
47 cout <P;
48 # endif
49 return * this;
50}
51
52 tlog & tlog: Operator <(string & S)
53 {
54 # ifdef log_stdout
55 cout <s;
56 # endif
57 Return * this;
58}
59 tlog & tlog: Operator <(tlog & (* pfun) (tlog &))
60 {
61 Return pfun (* This );
62}
63 tlog & Endl (tlog & object)
64 {
65 # ifdef log_stdout
66 cout <Endl;
67 # endif
68 return object;
69}
70
71 void tlog: Debug (const char * P)
72 {
73 * THIS <P;
74 return;
75}
76 void tlog: Debug (string & S)
77 {
78 * THIS <s;
79 return;
80}
81
82 void tlog: log (const char * P)
83 {
84 * THIS <log_prefix <p <Endl;
85
86 # ifdef log_syslog
87 syslog (log_info, P );
88 # endif
89 return;
90}
91 void tlog: log (string & S)
92 {
93 * THIS <log_prefix <S <Endl;
94
95 # ifdef log_syslog
96 syslog (log_info, S. c_str ());
97 # endif
98 return;
99}
100
101 int
102 main (void)
103 {
104 glog. Log ("yeetec ");
105 // glog. debug (_ FUNC __);
106 string word;
107 cout <"enter a line :";
108 CIN> word;
109 while (CIN. Get ()! = '/N ')
110 continue;
111 cout <word <"is all" <"wanted! /N ";
112
113 string line;
114 cout <"enter a line :( really )";
115 Getline (CIN and line );
116 cout <"line:" <line <Endl;
117 return 0;
118}
Result:
CT 16 16:01:42 Zerk A. Out: yeetec
This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/telehiker/archive/2007/10/18/1830575.aspx