多文件C程序,如何最好地实现可选的记录? [英] multi file C program, how best to implement optional logging?

查看:83
本文介绍了多文件C程序,如何最好地实现可选的记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多文件C程序。我希望用户能够在运行时指定不同的调试级别。

I have a multi file C program. I'd like the user to be able to specify different debugging levels at run time.

什么是实现这一目标的最佳方式是什么?

What is the best way to implement this?

我想有一个调试(水平,信息)类型的函数出口,到处被使用的。任何更好的/其他的想法?

I was thinking of having a debug(level, "message") type function exported and used everywhere. Any better/other ideas?

推荐答案

乔纳森的建议是好的,但因为C99我们有复杂的宏这样一个不需要用双括号调试宏。

Jonathan's suggestion is good but since C99 we have variadic macros so one doesn't need to use double braces for debug macro.

有日志记录是标题的轻型版本我使用的:

There is a light version of logging header I use:

#define LOG_FATAL    (1)
#define LOG_ERR      (2)
#define LOG_WARN     (3)
#define LOG_INFO     (4)
#define LOG_DBG      (5)

#define LOG(level, ...) do {  \
                            if (level <= debug_level) { \
                                fprintf(dbgstream,"%s:%d:", __FILE__, __LINE__); \
                                fprintf(dbgstream, __VA_ARGS__); \
                                fprintf(dbgstream, "\n"); \
                                fflush(dbgstream); \
                            } \
                        } while (0)
extern FILE *dbgstream;
extern int  debug_level;

所以,在我需要登录的东西,我只需要添加行像

So wherever I need to log something, I just add line like

LOG(LOG_ERR,I / O错误%s的发生,同时打开文件%s,字符串错误(错误),文件名);

程序初始化期间您需要为 dbgstream 指定的值(通常默认为标准错误)和 DEBUG_LEVEL

During program initialisation you need to specify values for dbgstream (usually defaults to stderr) and debug_level.

对于真正的项目,而不是调用 fprintf中很多时候我只是叫我的功能从 LOG 宏通 __ FILE __ __ LINE __ __ VA_ARGS _ 作为参数 - 该功能还会打印日期,时间和日志行PID,不要做 fflush()每一次 - 只有当缓冲计数器超过preSET价值 - itsignificantly增强了日志性能

For real projects instead of calling fprintf many times I just call my function from LOG macro and pass __FILE__, __LINE__ and __VA_ARGS_ as argument - that function also prints date, time and pid in log line, and don't do fflush() every time - only when buffering counter exceeds preset value - itsignificantly increases logging performance.

但请注意,因为它是只在C99引入了一些编译器可能不支持复杂的宏。

But please be aware that some compilers may not support variadic macros as it was introduced only in C99.

这篇关于多文件C程序,如何最好地实现可选的记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆