使用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. django-mysql表的增删改查

    1.增加数据 调用该路由执行ModelsCaozuo的处理方法 第一种实例化类 class ModelsCaozuo(View): ''' 数据库增加数据 ''' def get(self, requ ...

  2. nginx, supervisor

    Nginx(单进程): 反向代理, 负载均衡.图解 将配置文件 nginx.conf 的 user xx 配置好 xx用户 检查语法 $ sudo service nginx configtest 重 ...

  3. CSS层叠样式

    为了让网页元素的样式更加丰富,也为了让网页的内容和样式能拆分开,CSS由此思想而诞生,CSS是 Cascading Style Sheets 的首字母缩写,意思是层叠样式表.有了CSS,html中大部 ...

  4. linux随机数

    linux系统随机数生成;1,利用uuid(universally unique identifier),由open software foundation在distributed computing ...

  5. linux计划任务crontab的使用

    参考网站:https://www.cnblogs.com/intval/p/5763929.html 编辑计划任务:    crontab -e 查看计划任务:    crontab -l 使用实例: ...

  6. 4. java乱码处理

    //返回到jsp页面 //request.setCharacterEncoding("utf-8"); //response.setContentType("text/h ...

  7. 1.mysql ERROR 1045 (28000): 错误解决办法

    转自:https://www.cnblogs.com/jpwz/p/6061214.html ERROR 1045 (28000): Access denied for user 'ODBC'@'lo ...

  8. Unable to open file '.RES'

    Unable to open file '.RES' 另存工程,带来的隐患,工程图标也改不了. 搜索发现源码里某个man.cpp里带了prgram  resource aaa.res,换成新工程文件名 ...

  9. Kafka Manager 监控

    1.安装: 依赖java环境,须首先安装java运行环境,并正确设置路径. 确保kafka已经安装,且版本合适. 修改配置文件:   kafka-manager.zkhosts="你的zoo ...

  10. mongodb基础学习9-分片

    分片和复制集不同,复制集是多个实例存储相同的内容,而分片是将内容存储到不同的分片上,不同分片存储的数据不同 下面看看具体的操作: 先启动两个片的实例: 再启动configsvr,要加上configsv ...