开发者

C# log question

Does someone know any way to organize the logging statements more conveniently?

开发者_C百科

I guess there is no such way, but, well, here is a small example:

        // Take the longest path in the graph and convert it into the
        // image series, note that we project every element from the
        // sequence into the image path so that 'new Series(...)' constructor
        // could be used.
        var paths = EnumerateSimpleAndLoopedPaths().ToList();

        logger.Log(Something1);

        if (paths.Any())
        {
            // Take the longest possible path.
            var selectedPath = paths.OrderBy(x => x.Count()).Last();

            logger.Log(Something2);

            var imagesForSelectedPath = selectedPath.SelectMany(...

Obviously those logger.Log or Log or whatever statements are just like rubbish for the main code part, maybe there is a smart way to take them somewhere?

I know there are some nice packages, like PostSharp, which allows logging to be done before and after - but what if functions have to log some intermediate result of their work?

Or is this just a decomposition problem and I should make everything more decomposed so that I could mark all those loggable entries as [Loggable]?

Any suggestions would be appreciated. What do you do with logging in your code?


How about divided the inner logic of method to additional private methods to do the intermediate work,

or, if you don't want to end up with too many methods on class that can only be used in one place, ...

define an inner class to do the work (which automatically can access private members of parent class, if you pass reference to parent to inner class's constructor).
The inner class can have many private methods that can be accessed only by methods on the inner class. So define one public/internal method on inner class, to be called by method on outer class.

With both approaches, you can decorate new methods with attributes for AOP (e.g. PostSharp).


Due to the limitations of AOP frameworks, you'll need to use decomposition to get the benefit all the way around. You should be doing this anyway. Methods should be kept very simple and only do one thing. Extract out your conditional logic into a method(s) then create a PostSharp aspect.

I say this because if you need logging within your conditions then that block of code is significant enough to be in it's own method. Unless you're just doing it for tracing reasons in which case you can do whatever since it should be temporary anyway.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜