C language to achieve a simple level of write-log program

Source: Internet
Author: User
Tags sprintf
/************************************************************************/  /*    *   File name:write_log.cpp    *  pick      to: This file implements the log features in normal Windows programs     *            mainly has the following characteristics:    *            1.  Create a log file directory based on the date, which is stored in a different log directory each day;     *           2.  log content is divided into three types, according to different needs, Write log files of different log types,    *                convenient through the log positioning, analysis of problems;    *            3.  function through a better encapsulation, easy to reuse;    *             To be improved point:    *           1.  for convenience, The log content is printed with a time function, with a lower accuracy; &nbSp   *           2.  can encapsulate these functions as a log class, or a dynamic library, Make it more general;    *           3.  not consider cross-platform scenarios, Currently used only in Windows     *           4.  Log file content can also be further improved, such as printing out the current file name and line number, using the log function     *                more practical;    *    *  current version:1.0    *       :duanyongxing     *  Completion Date: October 11, 2009   */                                                                           /********************************** /   #ifndef  __WRITELOG_H__    #define  _ _writelog_h__    #include   "stdafx.h"     #include  <time.h>     #include  <memory.h>    #include  <stdio.h>    # include <stdlib.h>     #include  <stdarg.h>    #include  <windows.h>    #define  _LOG_WRITE_STATE_ 1             /*  conditional Compilation switch, 1: Write log, 0: Do not write log  */    #define   log_success  (0)     #define  LOG_FAILED   ( -1)     #define   log_bool_true  (1)     #define  LOG_BOOL_FALSE  (0)     #define   Dword_null   (0xFFFFFFFF)     #define  MAX_LOGTEXT_LEN  (2048)           /*  maximum length of log per line */    #define  MAX_FILE_PATH  (255)              /*  maximum length of log file path */    # define max_log_file_size  (512 * 1024)  /*  maximum length of log file content */    #define  MAX_LOG_FILE_NAME_LEN  (256)     /*  maximum length of log file name */        #define  LOG_TYPE_INFO    0              /*  Log type:  information type */    #define  LOG_TYPE_ERROR    1             /*  Log Type:  Error type */    #define  LOG_TYPE_SYSTEM  2              /*  Log Type:  system type */    #define  TEST_CASE_MAX_FILE_LEN  (1024)   Maximum length of file content in   /*  test function */    Const CharG_logrootpath[] = "C://my_applog"; /* Log file root path, specified by user/* #pragma pack (push, 1) typedef structTaglog_data/* Log content structure * * CharSTRDATE[11]; /* Date: Format For example: 2009-10-11*/ CharSTRTIME[9]; /* Time: Format For example: 16:10:57*/unsigned intItype; /* Log type: 3 kinds: INFO (0)/error (1)/system (2) * * CharStrtext[max_logtext_len];   /* Log Content * *}log_data, *lplog_data; #pragma pack (POP) intCreate_logdir ( Const Char*pstrpath); intCreate_logfile ( Const Char*pstrfile, intIPos); intIsfileexist ( Const Char*pstrfile); intGetlogpath ( Char*pstrpath); DWORDGetfilelenth ( Const Char*pfile); intWrite_log_text (Lplog_data lplogdata); voidWrite_log (unsigned intUilogtype, Char*PSTRFMT, ...); voidTestlogcase_one (); intMain intargc Char* argv[]) {Write_log (Log_type_system, "program begin.");    Testlogcase_one (); Write_log (Log_type_system, "program end."); return0; /********************************************************************* * Function name: void Testlogcase_one () Description: Simple test function, Read FILE * Caller: Main * input parameter: * NO * output parameter: * No * return value: * Void--* Author: duanyongxing * Time: 2009-10-11 ***************** ****************************************************/ voidTestlogcase_one () { FILE*pfile = NULL; Char*pfieldcontent = NULL; CharSzfilename[] = "Test_case.txt"; Pfieldcontent = ( Char*) malloc (Test_case_max_file_len); if(NULL = = pfieldcontent) {Write_log (Log_type_error, "malloc memory Failed,program exit!"); return;    } memset (pfieldcontent, 0, Test_case_max_file_len);    Write_log (Log_type_info, "malloc memory for pfiled successful,memory the size is:%ld", Test_case_max_file_len); PFile = fopen (szFileName, "R"); if(NULL = = pFile)           {fprintf (stderr, "Open file failed."); Write_log (Log_type_error, "Open file%s failed.") Program exit! ", szFileName); return;    }       write_log (log_type_info,  "open file %s  successful. ",  szfilename);    fread (pfieldcontent, 1, test_case_max_file_ Len, pfile);       pfieldcontent[test_case_max_file_len -1] =   '/0 ';        fclose (pFile);           printf ("the file %s content is: /n%s/n", szfilename,   pfieldcontent);    write_log (log_type_info,  "The file %s content is:  /n%s/n ",  szfilename,  pfieldcontent);  }  /**************************   *  function Name: Void write_log (unsigned int  uilogtype, char *pstrfmt,  ...)   *  Description: Log write function, support variable length parameter   *  Caller: Any place that needs to write a log   *  input parameters:  * unsigned itype --   log category   * char *pstrfmt  --   log content   *  ...            --   variable length parameter   *   OUTPUT parameter:  *  no   *  return value:  * void  --   *  author:  duanyongxing  *  Time  : 2009-10-11  ****************************************************** /   voidWrite_log (unsigned intUilogtype, Char*PSTRFMT, ...) {#if _log_write_state_/* Write the log or not compile switch/log_data DATA; time_tCurtime; struct TM*MT; va_listv1; memset (&data, 0, sizeof(Log_data));      Va_start (v1, pstrfmt);      _vsnprintf (Data.strtext, Max_logtext_len, pstrfmt, v1);      Va_end (v1);      Data.itype = Uilogtype;      Curtime = time (NULL);      MT = localtime (&curtime); Strftime (Data.strdate, sizeof(data.strdate), "%y-%m-%d", MT); Strftime (Data.strtime, sizeof(Data.strtime), "%h:%m:%s", MT);      Write_log_text (&data); #endif _log_write_state_}/********************************************************************* * Function name: int GetLog Path (char *pstrpath) * Description: Get log file path * Caller: Write_log_text * input parameter: * NO * output parameter: * Char *pstrpath * return value: * INT--Log_ FAILED: Failure *-Log_success: Success * Author: duanyongxing * Time: 2009-10-11 ******************************************* **************************/ intGetlogpath ( Char*pstrpath) { if(NULL = = Pstrpath) { returnlog_failed; } intIRet = 0; time_tCurtime = time (NULL); struct TM*MT = LocalTime (&curtime); /* Make folder name according to date/sprintf (Pstrpath, "%s//%d%02d%02d", G_logrootpath, Mt->tm_year + 1900, Mt->tm_mon + 1, m       T->tm_mday); IRet = Create_logdir (Pstrpath); returnIRet; /********************************************************************* * Function Name: int getlogfilename (int iLogType, const Char *pstrpath, char *pstrname) * Description: Get log file name * Caller: Write_log_text * Input parameters: * int Ilogtype--Log Type 3: INFO (0)/error (1)/system (2) * const char *pstrpath--log path obtained from Getlogpath * OUTPUT parameter: * Char *pstrname--Log file name * return value: * INT--log_failed: Failure *-Log_success: Success * Author: duanyongxing * Time: 2009-10-11 ******************************* **************************************/ intGetlogfilename ( intIlogtype, Const Char*pstrpath, Char*pstrname) { if(NULL = = Pstrpath) { returnlog_failed; } CharSzlogname[max_file_path]; FILE*pfile = NULL; memset (szlogname, 0, Max_file_path); Switch(Ilogtype) { Caselog_type_info:sprintf (Szlogname, "%s//app_info", Pstrpath); Break; Caselog_type_error:sprintf (Szlogname, "%s/
Related Article

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.