Nginx Log Class Interpretation

Source: Internet
Author: User

The Nginx log is defined in src/core/ngx_log.h|c and is the definition of nginx log-related structure and operation methods. Let's see what the log class is like:

1. log level definition :

#define NGX_LOG_STDERR            0
#define Ngx_log_emerg             1
#define Ngx_log_alert             2
#define Ngx_log_ Crit              3
#define NGX_LOG_ERR               4
#define Ngx_log_warn              5
#define Ngx_log_notice            6
#define NGX_LOG_INFO              7
#define NGX_LOG_DEBUG             8

Here defines 9 kinds of log levels, see the name of the macro to know the specific meaning.

The corresponding log level definitions are followed:

Static ngx_str_t err_levels[] = {
    ngx_null_string,
    ngx_string ("Emerg"),
    ngx_string ("alert")
    , Ngx_string ("Crit"),
    ngx_string ("error"),
    ngx_string ("Warn"),
    ngx_string ("notice"),
    ngx_ String ("Info"),
    ngx_string ("Debug")
};

2. Definition of debug Log type:

#define Ngx_log_debug_core        0x010
#define NGX_LOG_DEBUG_ALLOC       0x020
#define Ngx_log_debug_mutex       0x040
#define Ngx_log_debug_event       0x080
#define NGX_LOG_DEBUG_HTTP        0x100
#define Ngx_log _debug_mail        0x200
#define NGX_LOG_DEBUG_MYSQL       0x400

is the core module debug log, allocation log debugging, mutual-exclusion lock-related log debugging, event log debugging, HTTP log debugging, mail log debugging, MySQL log debugging.

The following is defined for the corresponding logging debug level:

static const char *debug_levels[] = {
    "Debug_core", "Debug_alloc", "Debug_mutex", "Debug_event",
    "debug_http "," Debug_mail "," Debug_mysql "
};

3. Below look at the ngx_log_t structure:

typedef ngx_log_s NGX_LOG_T;

struct ngx_log_s {
    ngx_uint_t           log_level;           Log level
    ngx_open_file_t     *file;                Log file
    ngx_atomic_uint_t    connection;          Atomic cell link

    ngx_log_handler_pt   handler;             Log processor
    void                *data;                Log Data
     * We declare "action" as "char *" because the actions are usually
     * the static strings and in the "U_char *" case we have to override
     * Their types all the time
     *                /char *action;              Operation
};

4. Ngx_errlog_commands nginx error log command set:

Static char *ngx_error_log (ngx_conf_t *cf, ngx_command_t *cmd, void *conf);      Error log processor pointer

static ngx_command_t  ngx_errlog_commands[] = {
    {ngx_string ("Error_log"),                        // Corresponds to the error_log instruction in the configuration, the file location of the log
     ngx_main_conf| Ngx_conf_1more,                   //belongs to the top-level configuration instruction
     Ngx_error_log,//                                  that is the error log processor
     0,
     0,
     NULL} above,
    Ngx_null_ Command
};
5. Ngx_errlog_module_ctx the context of the error log module

As mentioned earlier Nginx each module has its own context, the object is the context of the Nginx log, and the log module is also the core module.

Static ngx_core_module_t  ngx_errlog_module_ctx = {
    ngx_string ("ErrLog"),                      //Core module name
    NULL,                                      //Create a configured method pointer, null
    here Null                                       //Initialize method pointer for configuration, also null
} here;

6. Ngx_errlog_module error Log module Global object, which is stored in the compiled Ngx_modules array.

ngx_module_t  ngx_errlog_module = {
    NGX_MODULE_V1,                         //Here is the same as the general module, use this macro to initialize the contents of the previous 6 domains at once.
    &ngx_errlog_module_ctx,//                error log context
    Ngx_errlog_commands,                   //error log related command set
    ngx_core_module,                       //module type, error log as core module
    NULL,//initialize hook null for master process,//Initialize hook null for module,//Initialize
    process hook null,//                                  Initialize thread hook NULL,///exit hook NULL for thread,//exit hook NULL for process,//                                  exit Hook ngx_module_v1_ for Master process
    PADDING                  //Use this macro to initialize the contents of the last 8 domains at once
;
7. Several variables defined in the error log

Static ngx_log_t Ngx_log; Error Log Object
Static ngx_open_file_t Ngx_log_file; Error log file
ngx_uint_t ngx_use_stderr = 1; Whether standard errors are enabled

Which ngx_log_t described above, contains a log level, log files, atomic granularity, log processor, log data, and behavior information such as an object.

The following ngx_open_file_t structure is described below:

typedef ngx_open_file_s ngx_open_file_t;

struct ngx_open_file_s {
    ngx_fd_t              fd;                        Standard IO file descriptor
    ngx_str_t             name;                      File name
    void                (*flush) (ngx_open_file_t *file, ngx_log_t *log);  The refreshed handle
    void                 *data;                      Data
};

8. Ngx_log_init () method

In the previous introduction to the main function, we saw that the initialization of the log started with this function call, and the following is an analysis of the function and implementation of the functions.

ngx_log_t * Ngx_log_init (U_char *prefix) {U_char *p, *name;

    size_t Nlen, Plen;
    Ngx_log.file = &ngx_log_file;

    Ngx_log.log_level = Ngx_log_notice;   Name = (U_char *) Ngx_error_log_path; This looks like a macro definition after installation. Corresponds to the location of the log file/* We use Ngx_strlen () here since BCC warns about * condition is always false and unreachable

    Code */Nlen = Ngx_strlen (name);
        if (Nlen = = 0) {ngx_log_file.fd = Ngx_stderr;
    Return &ngx_log;

} p = NULL;  #if (Ngx_win32) if (name[1]!= ': ') {#else if (name[0]!= '/') {#endif if (prefix) {Plen =

        Ngx_strlen (prefix);
            else {#ifdef Ngx_prefix PREFIX = (U_char *) Ngx_prefix;
Plen = Ngx_strlen (prefix);
#else Plen = 0;
            #endif} if (plen) {name = malloc (Plen + Nlen + 2);
            if (name = = NULL) {return null; } p = ngx_cpymem (name, prefix,Plen);
            if (!ngx_path_separator (* (p-1))) {*p++ = '/';

            } ngx_cpystrn (P, (U_char *) Ngx_error_log_path, Nlen + 1);
        p = name; } NGX_LOG_FILE.FD = Ngx_open_file (name, Ngx_file_append, Ngx_file_create_or    _open, ngx_file_default_access);
                       Open the log file in attach mode if the file does not exist and set the default Access permission if (NGX_LOG_FILE.FD = = ngx_invalid_file) {Ngx_log_stderr (Ngx_errno, "[Alert] could not open error log file:" Ngx_open_file_n "\"%s\ "Failed", NA
ME);
                       #if (Ngx_win32) ngx_event_log (Ngx_errno, "Could not open error log file:"
Ngx_open_file_n "\"%s\ "failed", name);
    #endif ngx_log_file.fd = Ngx_stderr;
    } if (p) {Ngx_free (P);                                } return &ngx_log;
Returns the Log object. }

The above method initializes the log object Ngx_log, sets the default log level to Ngx_log_notice, sets the file handle for its file object, and uses the default standard error output log if the file location of the log record is not set.

9. Ngx_log_create (ngx_cycle_t *cycle, ngx_str_t *name): The creation of a log operation file that is managed uniformly in a pool of memory.

We know that the Nginx memory pool is used to manage the use and revocation of memory and resources uniformly, in addition to the start of the system log, other places need to use the file open and closed, are unified in the memory pool management, so as to avoid the constant creation and revocation of resources, as well as programming more trouble.

The function is to provide an interface for other places to use to log objects, and to manage log objects through the memory pool, which is the creation of log objects.

ngx_log_t *
ngx_log_create (ngx_cycle_t *cycle, ngx_str_t *name)
{ngx_log_t *log  ;

    Log = Ngx_pcalloc (Cycle->pool, sizeof (ngx_log_t));   Create a piece of memory in the memory pool to store the log object
    if (log = = null) {return
        null;
    }

    Log->file = Ngx_conf_open_file (cycle, name);        Open the file through the memory pool unified management, indexed according to the file name.
    if (log->file = = null) {return
        null;
    }

    return log;
}

About memory pool management, which will be added later. It's not going to go deep.

Ngx_log_error_core () function

Given the different operating systems, this function is implemented in a different way, only one implementation is spoken here.

The method is a variable number of parameters, preceded by a few parameters of ngx_uint_t level, ngx_log_t *log, ngx_err_t err,const Char *fmt, which are error levels, log objects, error objects, and the format of the log records.

The next variable parameter portion is the corresponding value parameter of the variable inside the format.

#if (Ngx_have_variadic_macros) void Ngx_log_error_core (ngx_uint_t level, ngx_log_t *log, ngx_err_t err, const char *F

MT, ...) 
#else void Ngx_log_error_core (ngx_uint_t level, ngx_log_t *log, ngx_err_t err, const char *FMT, va_list args) #endif
    {#if (Ngx_have_variadic_macros) va_list args; #endif u_char *p, *last, *msg;

    U_char ERRSTR[NGX_MAX_ERROR_STR];
    if (log->file->fd = = Ngx_invalid_file) {return;

    Last = Errstr + ngx_max_error_str;

    ngx_memcpy (Errstr, Ngx_cached_err_log_time.data, Ngx_cached_err_log_time.len);

    p = errstr + Ngx_cached_err_log_time.len;

    p = ngx_slprintf (p, Last, "[%V]", &err_levels[level]);

    /* Pid#tid * p = ngx_slprintf (p, last, "%p#" ngx_tid_t_fmt ":", Ngx_log_pid, Ngx_log_tid);
    if (log->connection) {p = ngx_slprintf (p, last, "*%ua", log->connection);

msg = p; #if (Ngx_have_variadic_macros) va_start (args, FMT);
    p = ngx_vslprintf (p, last, FMT, args);

Va_end (args);

#else p = ngx_vslprintf (p, last, FMT, args);
    #endif if (err) {p = Ngx_log_errno (p, last, err);
    } if (Level!= ngx_log_debug && log->handler) {p = Log->handler (LOG, p, last-p);
    } if (P > last-ngx_linefeed_size) {p = last-ngx_linefeed_size;

    } ngx_linefeed (P);

    (void) ngx_write_fd (LOG->FILE->FD, Errstr, P-ERRSTR); 
    if (!ngx_use_stderr | | level > Ngx_log_warn | | | log->file->fd = = ngx_stderr) {return;

    MSG-= (7 + err_levels[level].len + 3);

    (void) ngx_sprintf (msg, "Nginx: [%V]", &err_levels[level]);
(void) Ngx_write_console (Ngx_stderr, MSG, p-msg); }

The code for this method, as above, is the function of logging to a file or directly outputting it to the console.

11. Some of the remaining methods are basically a kind of packaging for logging, as well as setting the log level and so on, the method is relatively simple, here is not described in detail.


By the way, continue to mention the resource management of the memory pool, add a word, here see there are ngx_log_create, to create the method of the log object, but there is no closed handle, this is because the memory pool will be unified for the destruction processing, in processing a request, will automatically clean out.

Also give an example of a module that uses this method:

Src/http/ngx_http_core_module.c:clcf->error_log = Ngx_log_create (cf->cycle, &name);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.