如何在C程序中将日志记录逻辑与业务逻辑分开?而在C ++中呢? [英] How to separate logging logic from business logic in a C program? And in a C++ one?

查看:136
本文介绍了如何在C程序中将日志记录逻辑与业务逻辑分开?而在C ++中呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在用C进行编码,并且我有很多printfs,以便有时可以跟踪应用程序的流程.问题在于,有时候我需要比其他人更多的细节,因此我通常花时间注释/取消注释我的C代码,以便获得适当的输出.

I am currently coding in C and I have lots of printfs so that I can track, at some times, the flow of my application. The problem is that some times I want more detail than others, so I usually spend my time commenting/uncommenting my C code, so I can get the appropriate output.

使用Java或C#时,通常可以使用Aspects将实现代码和日志记录逻辑分开.

When using Java or C#, I can generally separate both my implementation code from the logging logic by using Aspects.

您是否在C中使用了类似的技术来解决此问题?

Is there any similar technique you use in C to get around this problem?

我知道我可以放置一个称为DEBUG的标志,该标志可以打开或关闭,因此我不必每次都想显示或隐藏printfs时就对整个代码进行注释/取消注释.问题是我还想摆脱代码中的日志记录逻辑.

I know I could put a flag called DEBUG that could be either on or off, so I wouldn't have to go all around and comment/uncomment my whole code every time I want to either show or hide the printfs. The question is I'd like to also get rid of the logging logic in my code.

如果我不是用C而是用C ++编写代码,那会更好吗?

If instead of C I was coding in C++, would it be any better?

似乎有一个AspectC ++,因此对于C ++似乎有一个解决方案.那C呢?

It seems there is an AspectC++, so for C++ there seems to be a solution. What about C?

谢谢

推荐答案

IME,您无法真正将日志记录与要登录的算法分开.战略性地放置日志记录 需要时间和经验 .通常,代码在整个生命周期中都会不断汇编日志记录语句(尽管它是渐近的).通常, 日志记录随代码一起发展 .如果算法经常更改,则日志记录代码通常也会更改.

IME you cannot really separate logging from the algorithms that you want to log about. Placing logging statements strategically takes time and experience. Usually, the code keeps assembling logging statements over its entire lifetime (though it's asymptotic). Usually, the logging evolves with the code. If the algorithm changes often, so will usually the logging code.

您可以做的是使日志记录尽可能 .也就是说,确保日志记录语句始终是一类的,不会干扰算法的读取,因此其他人可以在无需完全了解日志记录库等的情况下将其他日志记录语句插入现有算法中.

What you can do is make logging as unobtrusive as possible. That is, make sure logging statements always are one-liners that do not disrupt reading the algorithm, make it so others can insert additional logging statements into an existing algorithm without having to fully understand your logging lib, etc.

简而言之, 处理日志记录就像对待字符串处理一样 :将其包装在一个不错的小库中,该库将在几乎所有地方都包含和使用,以使该库快速,并使其易于使用.

In short, treat logging like you treat string handling: Wrap it in a nice little lib that will be included and used just about everywhere, make that lib fast, and make it easy to use.

这篇关于如何在C程序中将日志记录逻辑与业务逻辑分开?而在C ++中呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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