将终端打印定向到log文件中

本文介绍了一个使用C++进行日志输出的例子,通过复制文件描述符将标准错误输出重定向到指定的日志文件中,并利用syslog进行日志记录。
//main.cpp
#include <syslog.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string>
#include <assert.h>

int foo(void) {
    int fd = 0;
    fd = open("1.log",O_RDWR | O_CREAT | O_APPEND,0644);  /* 1.log的文件描述符是fd */
    if( -1 == fd) {
        printf("open 1.log file failed \n");
        return -1;
    }
    close(STDERR_FILENO);   /* 关闭STDERR_FILENO描述符 */
    dup2(fd,STDERR_FILENO); /* 复制文件描述符fd到STDERR_FILENO */
    close(fd);          /* 关闭文件描述符fd */
    openlog("1.log",LOG_PERROR,LOG_DAEMON);  /* 根据LOG_PERROR,将日志输出STDERR_FILENO定向到1.log  */
    return 0;
}

int main () {
    int ret = 0;
    ret = foo();
    if (0 != ret) {
        printf("error\n");
    }
    syslog(LOG_DEBUG,"hello world\n");
    return 0;
}

/*
g++ main.cpp
./a.out

cat 1.log
1.log: hello world

*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值