Cocoa Lumberjack: how to show file and line number?

跟風遠走 提交于 2019-12-03 14:02:04

问题


I am trying to find a way for Cocoa Lumberjack to show me file and line number.

After looking through the docs and some Googling, I found no easy way to do this.

Is there any way to do this without adding custom formatter?


回答1:


Well, like I said, there is no built-in way. So, I've implemented custom formatter:

@interface LineNumberLogFormatter : NSObject<DDLogFormatter>

- (NSString *)formatLogMessage:(DDLogMessage *)logMessage;

@end

@implementation LineNumberLogFormatter
- (NSString *)formatLogMessage:(DDLogMessage *)logMessage
{
    NSString *path = [NSString stringWithCString:logMessage->file encoding:NSASCIIStringEncoding];
    NSString *fileName = [path lastPathComponent];
    return [NSString stringWithFormat:@"%@:%d %@", fileName, logMessage->lineNumber, logMessage->logMsg];
}
@end



回答2:


While a separate formatter class would work, it would make your logging code a bit more verbose. In my project I opted for adding some additional macros that make use of CocoaLumberjack like so:

// Prefix.pch file
// ...

#ifdef DEBUG
#define DLogError(fmt, ...) DDLogError((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
#define DLogWarn(fmt, ...) DDLogWarn((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
#define DLogInfo(fmt, ...) DDLogInfo((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
#define DLogDebug(fmt, ...) DDLogDebug((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
#define DLogVerbose(fmt, ...) DDLogVerbose((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
#else
#define DLogError(fmt, ...)
#define DLogWarn(fmt, ...)
#define DLogInfo(fmt, ...)
#define DLogDebug(fmt, ...)
#define DLogVerbose(fmt, ...)
#endif

In your client code, you could then call:

DLogWarn(@"This is a warning");



回答3:


As UrK suggested, there isn't any trivial way, but it's pretty simple if you define your own formatter (see doc)



来源:https://stackoverflow.com/questions/19137867/cocoa-lumberjack-how-to-show-file-and-line-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!