原文

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef WIN32
#include <windows.h>
#include <io.h>
#else
#include <unistd.h>
#include <sys/time.h>
#include <pthread.h>
#define CRITICAL_SECTION pthread_mutex_t
#define _vsnprintf vsnprintf
#endif
//Log{
#define MAXLOGSIZE 100000000
#define ARRSIZE(x) (sizeof(x)/sizeof(x[0]))
#include <time.h>
#include <sys/timeb.h>
#include <stdarg.h>
char logfilename1[]="MyLog1.log";
char logfilename2[]="MyLog2.log";
char logstr[];
char datestr[];
char timestr[];
char mss[];
CRITICAL_SECTION cs_log;
FILE *flog;
#ifdef WIN32
void Lock(CRITICAL_SECTION *l) {
EnterCriticalSection(l);
}
void Unlock(CRITICAL_SECTION *l) {
LeaveCriticalSection(l);
}
#else
void Lock(CRITICAL_SECTION *l) {
pthread_mutex_lock(l);
}
void Unlock(CRITICAL_SECTION *l) {
pthread_mutex_unlock(l);
}
#endif
void LogV(const char *pszFmt,va_list argp) {
struct tm *now;
struct timeb tb; if (NULL==pszFmt||==pszFmt[]) return;
if (-==_vsnprintf(logstr,ARRSIZE(logstr),pszFmt,argp)) logstr[ARRSIZE(logstr)-]=;
ftime(&tb);
now=localtime(&tb.time);
sprintf(datestr,"%04d-%02d-%02d",now->tm_year+,now->tm_mon+,now->tm_mday);
sprintf(timestr,"%02d:%02d:%02d",now->tm_hour ,now->tm_min ,now->tm_sec );
sprintf(mss,"%03d",tb.millitm);
printf("%s %s.%s %s",datestr,timestr,mss,logstr);
flog=fopen(logfilename1,"a");
if (NULL!=flog) {
fprintf(flog,"%s %s.%s %s",datestr,timestr,mss,logstr);
if (ftell(flog)>MAXLOGSIZE) {
fclose(flog);
if (rename(logfilename1,logfilename2)) {
remove(logfilename2);
rename(logfilename1,logfilename2);
}
flog=fopen(logfilename1,"a");
if (NULL==flog) return;
}
fclose(flog);
}
}
void Log(const char *pszFmt,...) {
va_list argp; Lock(&cs_log);
va_start(argp,pszFmt);
LogV(pszFmt,argp);
va_end(argp);
Unlock(&cs_log);
}
//Log}
int main(int argc,char * argv[]) {
int i;
#ifdef WIN32
InitializeCriticalSection(&cs_log);
#else
pthread_mutex_init(&cs_log,NULL);
#endif
for (i=;i<;i++) {
Log("This is a Log %04d from FILE:%s LINE:%d\n",i, __FILE__, __LINE__);
}
#ifdef WIN32
DeleteCriticalSection(&cs_log);
#else
pthread_mutex_destroy(&cs_log);
#endif
return ;
}

最新文章

  1. [转]ASP.NET Core 之 Identity 入门(二)
  2. 登录到mysql查看binlog日志
  3. mac下限速
  4. JBossESB教程(一)——开发环境的搭建
  5. 第二篇:python基础之文件读写
  6. Cstyle的UEFI导读之SEC第一篇 Reset Vector
  7. ActionScript 3.0数组操作
  8. Unity扩展编辑器--类型3:Custom Editors
  9. java-创建线程的两种方式
  10. Linux命令--su与sudo
  11. 18、面向对象基本原则及UML类图简介
  12. child_process 子进程
  13. webpack 打包测试和生产多个版本
  14. rap使用手册
  15. BZOJ.4456.[ZJOI2016]旅行者(分治 Dijkstra)
  16. SQL SERVER深入学习学习资料参考
  17. MySQL(MariaDB)基础之一:编译安装
  18. 多年前写的DataTable与实体类的转换
  19. Web前端开发规范收集
  20. WCF wsdlexception(at/html):faultCode=INVALID_WSDL

热门文章

  1. GitHub 的简单使用
  2. uc浏览器的用户体验
  3. VS2015做单元测试
  4. HDU 5433 Xiao Ming climbing 动态规划
  5. [codecademy]css
  6. CA如何吊销签署过的证书
  7. 201621123037 《Java程序设计》第7周学习总结
  8. vue知识拓展
  9. JavaScript设计模式学习之路——面向对象的思想
  10. 各种GIT代码托管工具比较