简单c++日志类

C++实现简单的日志类(附完整源码) 阅读详情
/*
简单日志类
*/
#ifndef LOGGER_H_
#define LOGGER_H_
#include <string>
#include <time.h>
#include <Windows.h>
using namespace std;
//日志级别枚举  
typedef enum LogLevel  
{  
    信息 = 0,  //什么都不记录  
    错误,     //只记录严重错误  
    警告,     //记录严重错误,普通错误  
    致命,   //记录严重错误,普通错误,警告  
};  
class CLog{

public:
    CLog();
    ~CLog();
    //写日志方法
    void Log(string msg,LogLevel level );
protected:
    //初始化
    void GetExeName();
    //获取当前系统时间
    string GetCurrentTime();
    string m_Name;
    string m_Path;
};
#endif
#include "stdafx.h"
#include "Log.h"
#include <fstream>  
CLog::CLog()
{
    if (m_Name.size()>0) m_Name.clear();
    if (m_Path.size()>0) m_Path.clear();
    this->GetExeName();
    
}
CLog::~CLog()
{
    
}
void CLog::GetExeName()
{
    // 取进程执行文件名称
    char szExeName[MAX_PATH ]={0};  
    //GetModuleFileNameA(NULL, szExeName, MAX_PATH);
    if ( ::GetModuleFileNameA(NULL, szExeName, MAX_PATH) > 0)//获取当前进程已加载模块的文件的完整路径
    {
        char* pBegin = szExeName;
        char* pTemp  = szExeName;
        

        while ( *pTemp != 0 )
        {
            if ( *pTemp == '\\' )
            {
                pBegin = pTemp + 1;

            }
            pTemp++;

        }
        //(strrchr(szExeName, '\\'))[0] = 0; // 删除文件名,只获得路径字串  
        m_Path.insert(0,szExeName);
        m_Name.insert(0,pBegin);
        int a = m_Name.find('.');
        m_Name.erase(a);
        ZeroMemory(szExeName,sizeof(szExeName));
        sprintf_s(szExeName,"%s%s",m_Name.c_str(),".log");
        m_Name.clear();
        m_Name.insert(0,szExeName);
        
    }
}
void CLog::Log(string msg,LogLevel level )
{
    ofstream outfile;  
    outfile.open(m_Name.c_str(),ios::out|ios::app|ios::ate);
  switch(level)
  {
      case 信息:
          if (outfile.is_open()) outfile<<this->GetCurrentTime().c_str()<<m_Path.c_str()<<": "<<msg.c_str()<<" -->信息"<<endl;
          break;
      case 错误:
          if (outfile.is_open()) outfile<<this->GetCurrentTime().c_str()<<m_Path.c_str()<<": "<<msg.c_str()<<" -->错误"<<endl;
          break;
      case 警告:
          if (outfile.is_open()) outfile<<this->GetCurrentTime().c_str()<<m_Path.c_str()<<": "<<msg.c_str()<<" -->警告"<<endl;
          break;
      case 致命:
          if (outfile.is_open()) outfile<<this->GetCurrentTime().c_str()<<m_Path.c_str()<<": "<<msg.c_str()<<" -->致命"<<endl;
          break;
  }
  outfile.close();
}

string CLog::GetCurrentTime()
{
    struct tm t;   //tm结构指针
    time_t now;  //声明time_t类型变量
    time(&now);      //获取系统日期和时间
    localtime_s(&t, &now);   //获取当地日期和时间
    char temp[50] = {0};
    sprintf_s(temp,"[%d-%d-%d %d:%d:%d]" ,t.tm_year + 1900,t.tm_mon + 1,t.tm_mday,t.tm_hour,t.tm_min,t.tm_sec);    
    std::string  pTemp=temp;
    return pTemp;
}


C++高效日志类(库) 前段时间在做毕业设计需要有一个功能模块是写日志,为了配合高性能服务器不拖延服务器的效率所以必须要写出一个十分高效确不太占用系统资源的日志类。 经过参考前辈们写的资料加上自己不断地研究改进,现在完成了一个C++高效日志的类。经过我本人的测试发现该类库可以在WINDOWS平台、多线程环境下出色完成写日志的任务,可以达到50M/S的日志输出量。同时做了日志切割,当日志文件大小达到设定值时自动切入下一个文件,并用日期加序列号命名。 其中用到了BOOST多线程的锁,没有安装BOOST的机器可以屏蔽BOOST的相关代码,但是在多线程执行时会出错。 立即下载

相关推荐

CGNS快速入门到实战(一):CGNS静态链接库编译

近期,由于需要将CGNS格式加入到教研组自编CFD求解器DUBHE中,所以本人展开了对于CGNS的学习。CGNS快速入门到实战这一系列分成三篇文章展开叙述,具体有:(一)CGNS静态链接库编译;(二)VS配置调用CGNS静态链接库编写;(三)CGNS文件及案例展示。本篇文章重点讲述CGNS静态链接库编译。

ahang_99的博客 3819

C++日志类

//Log.h头文件 /* 简单日志类 */ #ifndef LOGGER_H_ #define LOGGER_H_ #include #include #include using namespace std; //日志级别枚举 typedef enum LogLevel { 信息 = 0, //什么都不记录 错误, //只记录严重错误 警告,

Syee001的专栏 500

SAP IDOC与EDI实战解析:从基础原理到跨系统采购订单同步

本文深入解析了SAP IDOC与EDI在企业数据交换中的核心作用,通过跨系统采购订单同步的实战案例,详细阐述了从基础原理到配置部署的全过程。文章将IDOC比作标准化数据“集装箱”,EDI视为高效传输“高速公路”,并提供了从消息类型定义、处理代码开发到全链路测试的完整指南,帮助企业实现自动化、无差错的业务协同。

weixin_28335283的博客 294

超级好用的C++实用库之日志类

日志类主要用于在程序运行过程中记录信息、错误、警告以及其他需要跟踪的数据,这对于调试、监控应用状态及后期问题分析至关重要。一个高效且灵活的日志类应该满足以下几个核心需求。日志级别管理:可定义多个日志级别,比如:DEBUG、INFO、WARN、ERROR、FATAL等,以便根据情况筛选日志的详细程度。同时,还允许运行时动态调整日志输出级别,便于在生产环境中减少不需要的日志输出,或增加更详细的日志输出。多线程安全:在多线程的环境下,可确保日志写入操作是线程安全的,避免日志内容混乱或程序崩溃。

hope_wisdom的技术博客 1558

WRF实战:自定义Vtable解析ECMWF海温数据的关键步骤与技巧

本文详细介绍了在WRF模型中自定义Vtable以解析ECMWF海温数据的关键步骤与技巧。通过解剖GRIB文件、编写自定义Vtable条目以及配置METGRID.TBL,解决了ECMWF数据与WRF模型对接的难题,为海洋气象和台风模拟研究提供了高精度数据输入方案。

weixin_29279101的博客 335

Vivado项目开发新思路:用VSCode写代码,用Vivado管理IP核与综合(Windows/Mac环境通用指南)

本文介绍了如何结合Vivado和VSCode的优势,打造高效的FPGA设计工作流。通过配置VSCode的Verilog插件和Vivado环境集成,开发者可以在VSCode中编写代码,同时利用Vivado管理IP核与综合,显著提升开发效率和团队协作体验。

weixin_42545503的博客 336

C++实现简单的日志类(附带源码)

在软件开发中,日志系统是不可或缺的部分。它能够帮助开发人员调试代码、分析错误,并记录程序运行时的关键信息

欢迎来到我的博客!这里是一个专注于计算机技术的分享平台,涵盖编程开发、算法研究、系统架构、软件工程等多个领域。无论你是初学者还是资深开发者,都能在这里找到有价值的内容。 819

CPU也能跑大模型?手把手教你用vLLM离线部署Qwen2.5-7B-Instruct(附性能优化技巧)

本文详细介绍了如何在CPU服务器上高效部署Qwen2.5-7B-Instruct模型,通过vLLM框架和一系列优化技巧实现离线推理。内容包括环境配置、模型加载优化、性能调优及生产环境部署方案,帮助开发者在资源有限的情况下也能运行大语言模型。

weixin_28691741的博客 489

C++类设计:一个不同版本的日志类(完整源码)

C++类设计:一个不同版本的日志类(完整源码)

编程之道在明明德在亲民在止于至善 1209

保姆级教程:QGC地面站Vehicle Setup全模块配置详解(从固件升级到安全设置)

本文提供QGC地面站Vehicle Setup全模块配置的保姆级教程,涵盖从固件升级到安全设置的完整流程。详细解析二次开发环境准备、传感器校准、飞行模式配置等关键步骤,帮助用户快速掌握无人机配置技巧,确保飞行安全与性能优化。

weixin_28726671的博客 385

精读204页华为的流程管理(文末附下载链接)

链接:https://pan.baidu.com/s/1eEwdBR5c0PIxkOrNhDZcGg?pwd=wha2 提取码:wha2 复制这段内容后打开百度网盘手机App,操作更方便哦。,以提升企业运营效率和竞争力,同时解决了诸多业务痛点,为华为的全球化发展提供了有力支撑。华为的流程管理对其发展起着关键作用,通过构建完善的流程体系,提升了企业运营效率与竞争力。华为的流程管理在企业发展中至关重要,其围绕。,并通过流程变革不断优化。在流程管理过程中,强调。构建了全面的流程体系。

cdfunlove的博客 282

一个简单的c++写日志类

在开发当中有的直接调试很方便,有的就不太好调试,所以我经常使用写日志以及输出Debug信息来进行开发。尽管我比较喜欢使用以输出Debug的信息的方式来跟踪程序。因为直接一句话: OutputDebugString("你想输出的信息\r\n"); 就可以在非调试模式下直接在DebugView上面显示输出信息了。 但是除了这种方式之外有时侯我也会使用写日志的方式来输出调试信息,虽然写文件很简单,但还是记录一下吧。方便自己同时也可能方便需要的人吧。 首先是main()函数定义: .

huang714的专栏 543

面向 Cloud Foundry、ABAP On-Prem 与 ABAP Cloud 的 SAP Fiori 开发全景:工具、流程与实战案例

SAP Fiori开发实战:基于BAS的一站式工程化方法 摘要: 本文系统梳理SAP Business Application Studio(BAS)在Fiori开发中的核心能力,提供三种典型后端(Cloud Foundry/ABAP On-Prem/ABAP Cloud)的对接方案。BAS通过预置Fiori Tools套件、MTA部署工具等扩展,支持从模板创建、可视化建模到构建部署的全流程。文章包含CAP+RAP服务对接、ABAP标准应用扩展等实战案例,重点解析注解驱动开发、Adaptation Proj

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 254

c++ 简单的日志类 CCLog

此日志类,简单地实现了向标准输出控制台和文件输出日志信息的功能,并能在这两者之间进行切换输出, 满足输出日志的不同需求。 代码如下: /* * CCLog.h * c++_common_codes * * Created by xichen on 12-1-12. * Copyright 2012 cc_team. All rights reserved

编程语言开发、框架原理、编程思想、最佳实践技巧经验分享。致力于各种编程技术的技巧经验干货分享,讲解开发避坑技巧,追踪开发前沿技术,实战展开解决难题。 程序员小迷助您在编程路上越走越好! 4016

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

一个简单可用的C++日志类

少废话,直接看东西。 //LogWriter.h #pragma once #include &lt;stdio.h&gt; #define LOG_BUFFER_SIZE 1024 class LogWriter { public: LogWriter(const char * filepath); ~LogWriter(void); bool write(con...

Ingvar 1977

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

C++ 最简单的日志类

最近搞一个 C++项目的二次开发,没玩过 C++,可谓步履维艰。自己写个简单的日志类都被各种坑折磨。终于搞定了。 参考了这篇博客,并且进一步简化:https://www.cnblogs.com/DswCnblog/p/5459539.html 代码如下: #pragma once #include <ctime> #include <iostream...

weixin_30776273的博客 276

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

最简单的C++日志类

最简单的C++日志类

CrazyFlyingBee的博客 760

C++简单实现一个日志类

C++ 没有貌似自带的日志类,如果仅仅使用cout输出调试信息的话比较凌乱,所以我尝试自己实现了一个Logger类,主要考虑实现以下功能: 日志等级: 参考python的logger类,我设置了四个日志等级, 从低到高依次为debug, info, warning, error,这样的话我想输出一条debug信息就可以这样写logger.debug("something..."), (关于日志等级是什么意思可以参考一下python的logger类,简单来说就是当日志等级大于等于设置的初始等级时才会记录日志

我的博客 9307

【C++11】实现一个简单的日志类

C++11实现的简单日志类

qq_36745595的博客 1351

C++ 简单的日志类

/* 简单的日志记录类. (日志而已,何必那么复杂!!!) W.J.Chang 2013.12.13 说明:(EasyLog.h) 1, 简单的单件实现(自动垃圾回收) 2, 使用方法:EasyLog::Inst()->Log("Run..."); 3, 日志记录结果:Run... [2013.12.13 16:38:42 Friday] */ #pragma once #ifndef EASY

Yours风之恋 ~~~~~ 3502

一个简单实用的C++日志类

        最近做c++开发,需要对软件状态做一个日志记录,发现开源的实现很多,但感觉太大了,动不动就几十个Cpp文件。我的东西还要跑在嵌入式设备上呢?不就写个日志吗,“”噼噼啪啪“”,一个下午就搞定! 在此做一个简单记录吧,供自己日后参考!    Log.H头文件 #pragma once #include &lt;fstream&gt; #include &lt;iostream&g...

liaogaobo2008的博客 681

一个简单的日志类Logger (windows版)

/ 文件创建时间的时间戳。

谢谢大家的关注和点赞!这里只有纯纯的知识干货,没有一句废话。希望能实实在在帮到大家~要是觉得有用,别忘了给我点支持哟,你 953
上一篇: c++stack容器介绍
下一篇: 使用c++11写个最简跨平台线程池(转载)
Syee001
博客等级 码龄14年 3粉丝 5原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值