使用ostream流创建写入log日志文件

使用宏 配置文件大小和间隔时间  当创建文件时间间隔或文件大小大于指定数字 则创建新文件

文件名由时间自动命名

/**************************************************************
技术博客 
技术交流群
群号码:324164944

欢迎c c++ windows驱动爱好者 服务器程序员沟通交流

**************************************************************/
#include "stdafx.h"
#include "StreamLog.h"
#include <sstream> namespace DEFTOOLS {
LogFile::LogFile():pOfsLogFile_(NULL){
filePath_ = "";
fileName_ = filePath_ + MakeFileName();
} LogFile::LogFile(const std::string& filePath): pOfsLogFile_(NULL){
filePath_ = filePath;
fileName_ = filePath_ + MakeFileName();
} const std::string LogFile::MakeFileName() {
struct tm t = tm_.GetCurrentDataTime();
std::stringstream s;
std::string str;
s << t.tm_year + << "_" << t.tm_mon + << "_"
<< t.tm_mday << "_" << t.tm_hour << "_" <<
t.tm_min << "_" << t.tm_sec << ".log";
s >> str;
return str;
}
bool LogFile::CreateFile() {
bool bRet = false;
try {
pOfsLogFile_ = new std::ofstream(fileName_.c_str(), std::ios_base::app);
if (NULL == pOfsLogFile_ || pOfsLogFile_->bad())
{
pOfsLogFile_ = NULL;
std::exception e("open ofstream error");
throw e;
}
tm_.SetBeginTime();
bRet = true;
}
catch (const std::exception& error)
{
std::cerr << error.what() << std::endl;
} return bRet;
} bool LogFile::InitFunc() {
return CreateFile();
} LogFile::~LogFile(){
if (NULL != pOfsLogFile_)
{
pOfsLogFile_->close();
delete pOfsLogFile_;
}
} void LogFile::CheckFile() {
tm_.SetEndTime();
if ((tm_.GetDeltaTime() > DEFAULT_DELTA_TIME) ||
GetFileSize() > DEFAULT_FILE_SIZE) {
if (NULL != pOfsLogFile_) {
pOfsLogFile_->close();
delete pOfsLogFile_;
pOfsLogFile_ = NULL;
}
fileName_ = filePath_ + MakeFileName();
CreateFile();
}
} const std::string LogFile::GetCurrentTimeString()
{
struct tm t = tm_.GetCurrentDataTime();
std::stringstream s;
std::string str;
std::string strTime;
s << t.tm_year + << "-" << t.tm_mon + << "-"
<< t.tm_mday;
s >> str;
s.clear();
s << t.tm_hour << ":" <<
t.tm_min << ":" << t.tm_sec << "\t\t";
s >> strTime; str += " ";
str += strTime;
return str;
} std::string LogFile::GetLevelString(const WriteLevel wl) {
std::string levelStr;
switch (wl)
{
case NORMAL_L:
levelStr = "[normal ]\t";
break;
case WARNING_L:
levelStr = "[warning]\t";
break;
case ERROR_L:
levelStr = "[error ]\t";
break;
case UNKNOWN_L:
levelStr = "[unknown]\t";
break;
default:
levelStr = "[???????]\t";
break;
}
return levelStr;
} bool LogFile::WriteLog( std::string wrtieStr, const WriteLevel wl) {
bool bRet = false;
CheckFile();
if (!pOfsLogFile_) {
return bRet;
}
(*pOfsLogFile_) << GetCurrentTimeString() << GetLevelString(wl) << wrtieStr << std::endl;
bRet = true;
return bRet;
} }//namespace DEFTOOLS
#pragma once

#include <time.h>
#include <string>
#include <fstream>
#include <iostream>
#include <string> namespace DEFTOOLS {
#define DEFAULT_DELTA_TIME (60*2) //日志切换时间
#define DEFAULT_FILE_SIZE (1024*1024*1024) //日志切换文件大小 typedef enum WRITE_LEVEL
{
NORMAL_L = ,
WARNING_L,
ERROR_L,
UNKNOWN_L
}WriteLevel; // Time 管理时间及时间差 以及年月日
class LogTime {
public:
LogTime() :timeBegin_(time(NULL)), timeEnd_(time(NULL)) {
time_t t = time(NULL);
localtime_s(&tm_, &t);
} void SetBeginTime() { timeBegin_ = time(NULL); }
void SetEndTime() { timeEnd_ = time(NULL); } time_t GetBeginTime() { return timeBegin_; }
time_t GetEndTime() { return timeEnd_; }
time_t GetDeltaTime() { return timeEnd_ - timeBegin_; }
struct tm GetCurrentDataTime() {
time_t t = time(NULL);
localtime_s(&tm_, &t);
return tm_;
};
private:
time_t timeBegin_;
time_t timeEnd_;
struct tm tm_;
}; class LogFile {
public:
LogFile();
LogFile(const std::string& filePath);
virtual ~LogFile();
bool InitFunc();
std::streampos GetFileSize() { if (!pOfsLogFile_) { return ; }return pOfsLogFile_->tellp(); };
void CheckFile();
bool WriteLog(const std::string wrtieStr, const WriteLevel wl = NORMAL_L);
//============================
void WriteFileTest() {
CheckFile();
if (!pOfsLogFile_){
return;
}
(*pOfsLogFile_) << "测试1234" << std::endl;
}
//============================
private:
bool CreateFile();
const std::string GetCurrentTimeString();
const std::string MakeFileName();
std::string LogFile::GetLevelString(const WriteLevel wl);
std::string fileName_;
std::string filePath_;
std::ofstream* pOfsLogFile_;
LogTime tm_;
}; }//namespace DEFTOOLS

运行效果图

c++日志练习的更多相关文章

  1. .NetCore中的日志(2)集成第三方日志工具

    .NetCore中的日志(2)集成第三方日志工具 0x00 在.NetCore的Logging组件中集成NLog 上一篇讨论了.NetCore中日志框架的结构,这一篇讨论一下.NetCore的Logg ...

  2. .NetCore中的日志(1)日志组件解析

    .NetCore中的日志(1)日志组件解析 0x00 问题的产生 日志记录功能在开发中很常用,可以记录程序运行的细节,也可以记录用户的行为.在之前开发时我一般都是用自己写的小工具来记录日志,输出目标包 ...

  3. Logstash实践: 分布式系统的日志监控

    文/赵杰 2015.11.04 1. 前言 服务端日志你有多重视? 我们没有日志 有日志,但基本不去控制需要输出的内容 经常微调日志,只输出我们想看和有用的 经常监控日志,一方面帮助日志微调,一方面及 ...

  4. SQLServer事务同步下如何收缩日志

    事务同步是SQLServer做读写分离的一种常用的方式. 随着业务数据的不断增长,数据库积攒了大量的日志,为了腾出硬盘空间,需要对数据库日志进行清理 订阅数据库的日志清理 因为订阅数据库所有的数据都来 ...

  5. 如何正确使用日志Log

    title: 如何正确使用日志Log date: 2015-01-08 12:54:46 categories: [Python] tags: [Python,log] --- 文章首发地址:http ...

  6. 前端学HTTP之日志记录

    前面的话 几乎所有的服务器和代理都会记录下它们所处理的HTTP事务摘要.这么做出于一系列的原因:跟踪使用情况.安全性.计费.错误检测等等.本文将谥介绍日志记录 记录内容 大多数情况下,日志的记录出于两 ...

  7. ASP.NET Core应用中如何记录和查看日志

    日志记录不仅对于我们开发的应用,还是对于ASP.NET Core框架功能都是一项非常重要的功能特性.我们知道ASP.NET Core使用的是一个极具扩展性的日志系统,该系统由Logger.Logger ...

  8. .NET Core的日志[5]:利用TraceSource写日志

    从微软推出第一个版本的.NET Framework的时候,就在“System.Diagnostics”命名空间中提供了Debug和Trace两个类帮助我们完成针对调试和跟踪信息的日志记录.在.NET ...

  9. .NET Core的日志[4]:将日志写入EventLog

    面向Windows的编程人员应该不会对Event Log感到陌生,以至于很多人提到日志,首先想到的就是EventLog.EventLog不仅仅记录了Windows系统自身针对各种事件的日志,我们的应用 ...

  10. .NET Core的日志[3]:将日志写入Debug窗口

    定义在NuGet包"Microsoft.Extensions.Logging.Debug"中的DebugLogger会直接调用Debug的WriteLine方法来写入分发给它的日志 ...

随机推荐

  1. IPv4检验和计算

    IP分组中的检验和仅覆盖首部,而不管数据,首部被划分为16位的段,把所有段相加,结果取反,塞进首部检验和里 在目的主机中,首部划分为16位,相加,结果肯定是16个1,然后取反,结果为0.如下 在目的主 ...

  2. openlayers3教材详解及demo(完整)

            openlayers3教材详解及demo(完整)        OpenLayers 3对OpenLayers网络地图库进行了根本的重新设计.版本2虽然被广泛使用,但从JavaScri ...

  3. leetcode925

    public class Solution { public bool IsLongPressedName(string name, string typed) { var list1 = new L ...

  4. C++Primer笔记-----day08

    ==========================================================================day08===================== ...

  5. rem 响应 js函数

    size();window.onresize = function(){ size();}function size(){ var htnl_o=document.getElementsByTagNa ...

  6. JAVA NIO学习记录2-非阻塞式网络通信

    一.阻塞与非阻塞 传统的IO 流都是阻塞式的.也就是说,当一个线程调用read() 或write() 时,该线程被阻塞,直到有一些数据被读取或写入,该线程在此期间不能执行其他任务.因此,在完成网络通信 ...

  7. jemalloc for mysql

    ptmalloc 是glibc的内存分配管理 tcmalloc 是google的内存分配管理模块 jemalloc 是BSD的提供的内存分配管理 三者jemalloc和tcmalloc的性能不分伯仲, ...

  8. scala-学习 2

    列表操作 List() 或者是 Nil 空list scala> val a = List() a:List[Nothing] = List() print(a.length) a.length ...

  9. js中声明函数的方法

    <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...

  10. Python模拟登录的几种方法

    目录 方法一:直接使用已知的cookie访问 方法二:模拟登录后再携带得到的cookie访问 方法三:模拟登录后用session保持登录状态 方法四:使用无头浏览器访问 正文 方法一:直接使用已知的c ...