编写日志写入函数(包装 vfprintf): how to modify the text string to print?

标签 c linux format printf

我正在编写一个日志编写器,为此我正在 vfprintf 上编写一个包装函数,以便我能够在它周围包含一些额外的信息。

日志写入宏定义如下:

#define LOG_WRITE(type, fmt, args...)   write_log(type, __FILE__, __FUNCTION__, __LINE__, fmt, ## args)

我的函数定义如下:

int write_log(enum LogType_e type, const char* file, const char* function, int line, const char* format, ...) {

    va_list arg;
    int rv;

    va_start(arg, format);
    rv = vfprintf(log_fd, format, arg);
    va_end(arg);

    return rv;
}

该函数获取一些额外信息,例如日志级别、运行日志调用的文件、函数、代码行,最后是文本。

当然,我想检查该信息并对其进行良好的格式化并将其添加到“格式”中。我怎样才能做到这一点?

最佳答案

最简单的解决方案可能不是修改格式字符串,而是添加对 fprintf(log_fd, ...) 的进一步调用:

void write_log(enum LogType_e type, const char* file, const char* function, int line, const char* format, ...) {

    va_list arg;
    int rv;

    switch (type) {
    case TYPE_ERROR:
        fprintf(log_fd, "Error: ");
        break;
    case TYPE_WARN:
        fprintf(log_fd, "Warning: ");
        break;
    }

    if (file) {
        if (function) {
            fprintf(log_fd, "[%s in %s, %d] ", function, file, line);
        } else {
            fprintf(log_fd, "[%s, %d] ", file, line);
        }
    }

    va_start(arg, format);
    rv = vfprintf(log_fd, format, arg);
    va_end(arg);
}

这使得跟踪打印的字符数变得更加困难,但无论如何您都不会使用该信息,因此计算和返回它是没有意义的。

(如果需要自动换行,您也可以记录到临时字符串,然后漂亮地打印该字符串。但这意味着您必须再次跟踪整个字符串长度。)

关于编写日志写入函数(包装 vfprintf): how to modify the text string to print?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22685895/

相关文章:

c - 在C中添加到链表的尾部

c - 温索克 : UDP recvfrom() not filling in the same IP address that was used to send data

linux - 告诉哪个版本的符号可用于链接(在 libc 中)?

java - 格式持续时间

python - print 和 format() 输出的 unicode 字符串不一致

c - 在 C 中查找 malloc() 数组长度?

c++ - GTK+上的中小型开源项目示例

linux - 在 GNU/Linux 中,匹配文件中的模式并使用找到的字符串提取包含另一个文件中的字符串的行

linux - 在 bash 中比较文件的更快解决方案

c++ - 使用 double 值的货币格式