日志记录工具 C++ linux

这篇博客介绍了如何使用C++编写一个简单的日志管理类,包括文件的创建、写入和删除功能。类构造函数利用当前时间创建文件名,使用mkpath函数创建目录并打开文件。文件写入时会附带时间戳,delete_old_file函数负责删除过期日志。此外,还提供了获取文件修改时间及获取文件夹中所有.txt文件的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

介绍

使用logfile.h 和 logfile.cpp 两个文件实现功能.

class类定义

#include<ros/ros.h>
#include<fstream>
#include<sys/types.h>
#include<sys/stat.h>//引入系统库,使用该库中的方法创建文件夹
#include<iostream>
#include<dirent.h>//文件夹处理相关函数库

#include<string>
#include<vector>


class logfile{
public:
    logfile(std::string dirname); 
    logfile();
    ~logfile();
    bool write(std::string msg);
    void delete_old_file(const long deadline);

private : 
    std::string dir; 
    std::fstream fs; 

    void get_files(std::vector<std::string> &filelist);
    long get_file_modify_time(std::string filepath);
    int mkpath(std::string s, mode_t mode = 755);
};



构造函数

构造函数通过私有函数mkpath先创建路径,再使用程序执行的时间作为文件名创建文件,并打开该文件.文件对象被成员变量fs持有.

logfile::logfile() { 
    new (this)logfile("./data/logfile"); 
    }

logfile::logfile(std::string dirname){ 
    dir = dirname;
    time_t now = time(0);      //日历时间1970.1.1以来的秒数
    tm *tc = localtime(&now);  //返回本地时间的结构体指针 
    mode_t mode = 0755;  // mode用于设置文件夹权限  755
    // std::string dir ="./logfile";
    // int mdret = ::mkdir(dirname.c_str(), mode);  //调用Linux 系统的 ::mkdir 方法创建文件夹,应该在调用时创建文件
    int mdret = mkpath(dirname, mode); 
    //创建并打开新文件写入数据
    std::string filename =
        std::to_string(tc->tm_year + 1900) + '-' + std::to_string(tc->tm_mon + 1) + '-' + std::to_string(tc->tm_mday)
    +'-' + std::to_string(tc->tm_hour) + '-' + std::to_string(tc->tm_min);
    filename = dirname + "/" + filename + ".txt"; 
    fs.open(filename, std::ios::in | std::ios::out | std::ios::app); 

    if (fs.is_open()) {
        ROS_INFO("create new logfile: [%s]", filename.c_str());
    } else {
        std::cout << "file open error" << std::endl;
    } 
}


int logfile::mkpath(std::string s, mode_t mode) { 
    
    size_t pre = 0, pos;
    std::string dir;
    int mdret;

    if(s[s.size()-1]!='/'){
        s += '/';
    }

    while((pos=s.find_first_of('/',pre))!=std::string::npos){
        dir = s.substr(0, pos++);
        pre = pos;
        if (dir.size() == 0) continue;
        if((mdret=::mkdir(dir.c_str(),mode))&&errno!=EEXIST){
            return mdret;
        }
    }
    return mdret;
}

文件写入函数

文件写入时加入写入时间,并简单格式化.

bool logfile::write(std::string msg) {
    // std::cout << dir << std::endl;
    time_t now = time(0);      //日历时间1970.1.1以来的秒数
    tm *tc = localtime(&now);  //返回本地时间的结构体指针

    std::string input_time = std::to_string(tc->tm_year + 1900) + '-' + std::to_string(tc->tm_mon + 1) + '-' +
                             std::to_string(tc->tm_mday) + "   " + std::to_string(tc->tm_hour) + ':' +
                             std::to_string(tc->tm_min) + ":" + std::to_string(tc->tm_sec);

    std::string st = input_time + "\n" + msg.c_str() + "\n";
    // std::cout << st << std::endl;

    fs << st;
    ROS_INFO("write success");
    // ROS_INFO("Log file write: [%s]", msg.c_str());  //在terminal中输出写入的数据
    }

文件删除函数

作为日志记录,应该具有旧文件删除功能.


void logfile::delete_old_file(const long deadline){
    std::vector<std::string> filelist;
    get_files(filelist); 
    long temp_time = 0; 

    for (auto it = filelist.begin(); it < filelist.end(); ++it)
    {  
        temp_time = get_file_modify_time(it->c_str()); 
        if(temp_time<deadline){ 
            remove(it->c_str());
            ROS_INFO("reomove old file: [%s]", it->c_str());
        }
    }
}


//获取一个文件的最近更新时间
long logfile::get_file_modify_time(std::string filepath){
    struct stat filehand;//stat 数据结构中包含文件描述信息
    FILE *fp;
    fp = fopen(filepath.c_str(), "r");//文件打开后才能获取其 stat
    int fileid = fileno(fp);//使用fileno方法获取文件描述符
    fstat(fileid, &filehand);//给stat结构体赋值
    fclose(fp);//获得stat后关闭文件
    return filehand.st_mtime;//返回最近更新时间
}

//获取文件夹中所有.txt文件
void logfile::get_files( std::vector<std::string>&filelist){ 
    if(dir.empty())
        return; 
    struct stat s;
    stat(dir.c_str(), &s);//获取dirname的文件状态,状态信息存入stat结构s中
    if(!S_ISDIR(s.st_mode)) //判断路径是不是目录
        return; 
    DIR *dirhand = opendir(dir.c_str());
    if(NULL == dirhand){
        //std::cout << "文件夹为空" << std::endl;
        return;
    } 
    dirent *fp = nullptr;
 
    while((fp = readdir(dirhand)) != nullptr){
        if(fp->d_name[0] !=  '.'){ //忽略隐藏文件夹
            std::string filename = dir + "/" + std::string(fp->d_name);//获取文件名
            struct stat filemod;
            stat(filename.c_str(), &filemod);//获取文件状态信息 
            if(S_ISREG(filemod.st_mode)){//如果文件为普通文件
                std::string file_extension = filename.substr(filename.length() - 4, filename.length());
                if(file_extension.compare(".txt") == 0)//如果文件以 .txt 结尾
                    filelist.push_back(filename);
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值