How to implement log function in daemon system

   This article is about to implement a loging function in a daemon system, under linux system and using C programing language.

   The loging module have several log level, like LOG_LEVEL_EMPTY, LOG_LEVEL_CRIT etc. With these different levels the programmers can log various running infomation to the log file, and it can offer you a unify and clear messages. This module should have a public interface and suppose we call it daemon_log.

   Here is the declaration of this interface:

       void daemon_log(int level, const char *fmt, ...);

   The logging module implements two methods for save messages one is regular file and the other is system log. So we can provide the following interface:

       int daemon_open_log(int type, int level, const char *filename);

   This function have three parameters, type corresponding to log type, and it can be LOG_TYPE_FILE or LOG_TYPE_SYSLOG; level corresponding to log level, it can be LOG_LEVEL_CRIT or LOG_LEVEL_INFO etc; filename corresponding to the file name if the type is set to LOG_LEVEL_FILE.


int daemon_open_log(int type, int level, const char *filename)
{
    FILE *log_file = NULL;
    log_level = level;
    if (LOG_LEVEL_EMPTY == level)
        return SUCCEED;
    if (LOG_TYPE_FILE == type && NULL == filename)
        type = LOG_TYPE_SYSLOG;
    if (LOG_TYPE_SYSLOG == type)
    {
        log_type = LOG_TYPE_SYSLOG;
        openlog(application_title, LOG_PID, LOG_DAEMON);
    }
    else if (LOG_TYPE_FILE == type)
    {
        if (MAX_STRING_LEN <= strlen(filename))
        {
            ntm_error("too long path for logfile");
            exit(FAIL);
        }
        if (NTM_MUTEX_ERROR == ntm_mutex_create_force(&log_file_access, NTM_MUTEX_LOG))
        {
            ntm_error("unable to create mutex for log file");
            exit(FAIL);
        }
        if (NULL == (log_file = fopen(filename, "a+")))
        {
            ntm_error("unable to open log file [%s]: %s", filename, ntm_strerror(errno));
            exit(FAIL);
        }
        log_type = LOG_TYPE_FILE;
        strscpy(log_filename, filename);
        ntm_fclose(log_file);
    }
    return SUCCEED;
}


Not finished......




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章