log4j2中文手册(6)

2019-04-13 18:06

41. privateString createUpdateString(){ 42. } 43.

44. privateString createQueryString(){ 45. } 46.

47. privateString formatCols(Map cols){ 48. StringBuilder sb =newStringBuilder(); 49. boolean first =true;

50. for(Map.Entry entry : cols.entrySet()){ 51. if(!first){ 52. sb.append(\); 53. }

54. sb.append(entry.getKey()).append(\).append(entry.getValue()); 55. first =false; 56. }

57. return sb.toString(); 58. } 59. }

接着我们可以使用定义的 SQLMessage

1. import org.apache.logging.log4j.Logger; 2. import org.apache.logging.log4j.LogManager; 3. import java.util.Map; 4.

5. publicclassMyApp{ 6.

7. privateLogger logger =LogManager.getLogger(MyApp.class.getName()); 8. privatestaticfinalMarker SQL_MARKER =MarkerManager.getMarker(\);

9. privatestaticfinalMarker UPDATE_MARKER =MarkerManager.getMarker(\, SQL_MARKER); 10. privatestaticfinalMarker QUERY_MARKER =MarkerManager.getMarker(\, SQL_MARKER); 11.

12. publicString doQuery(String table){ 13. logger.entry(param); 14.

15. logger.debug(QUERY_MARKER,newSQLMessage(SQLMessage.SQLType.QUERY, table)); 16.

17. return logger.exit(); 18. } 19.

20. publicString doUpdate(String table,Mapparams){ 21. logger.entry(param); 22.

23. logger.debug(UPDATE_MARKER,newSQLMessage(SQLMessage.SQLType.UPDATE, table, parmas); 24.

25. return logger.exit(); 26. } 27. }

可以看到,这个例子中,原来业务逻辑中格式化 SQL列的操作被放在了 SQLMessage中,如果需要,还可以在Filters和 Layouts中队这个 SQLMessage进行特殊处理。

Log4j2提供了了一些方便的 Message实现:

? FormattedMessage

The message pattern passed to a FormattedMessage is first checked to see if it is a valid

java.text.MessageFormat pattern. If it is, a MessageFormatMessage is used to format it. If not it is next checked to see if it contains any tokens that are valid format specifiers for String.format(). If so, a

StringFormattedMessage is used to format it. Finally, if the pattern doesn't match either of those then a ParameterizedMessage is used to format it. ? LocalizedMessage

LocalizedMessage is provided primarily to provide compatibility with Log4j 1.x. Generally, the best approach to localization is to have the client UI render the events in the client's locale.

LocalizedMessage incorporates a ResourceBundle and allows the message pattern parameter to be the key to the message pattern in the bundle. If no bundle is specified, LocalizedMessage will attempt to locate a bundle with the name of the Logger used to log the event. The message retrieved from the bundle will be formatted using a FormattedMessage. ? LoggerNameAwareMessage

LoggerNameAwareMessage is an interface with a setLoggerName method. This method will be called during event construction so that the Message has the name of the Logger used to log the event when the message is being formatted. ? MapMessage

A MapMessage contains a Map of String keys and values. MapMessage implements FormattedMessage and accepts a format specifier of \formatted as \? MessageFormatMessage

MessageFormatMessage handles messages that use a conversion format. While this Message has more flexibility than ParameterizedMessage, it is also about two times slower. ? MultiformatMessage

A MultiformatMessage will have a getFormats method and a getFormattedMessage method that accepts and array of format Strings. The getFormats method may be called by a Layout to provide it information on what formatting options the Message supports. The Layout may then call getFormattedMessage with one or more for the formats. If the Message doesn't recognize the format name it will simply format the data using its default format. An example of this is the StructuredDataMessage which accepts a format String of \cause it to format the event data as XML instead of the RFC 5424 format. ? ObjectMessage

Formats an Object by calling its toString method. ? ParameterizedMessage

ParameterizedMessage handles messages that contain \the replacement parameters. ? SimpleMessage

SimpleMessage contains a String that requires no formatting. ? StringFormattedMessage

StringFormattedMessage handles messages that use a conversion format that is compliant with java.lang.String.format(). While this Message has more flexibility than ParameterizedMessage, it is also 5 to 10 times slower. ? StructuredDataMessage

StructuredDataMessage allows applications to add items to a Map as well as set the id to allow a message to be formatted as a Structured Data element in accordance withRFC 5424. ? ThreadDumpMessage

A ThreadDumpMessage, if logged, will generate stack traces for all threads. If running on Java 6+ the stack traces will include any locks that are held. ? TimestampMessage

A TimestampMessage will provide a getTimestamp method that is called during event construction. The timestamp in the Message will be used in lieu of the current timestamp.

5. Thread Context

Log4j引入了 MDC(Mapped Diagnostic Context) 与 NDC的概念, MDC&NDC 概念详见http://www.ibm.com/developerworks/cn/web/wa-lo-usertrack/index.html#userTrackSample

例如在WEB环境下,所有用户的日志都会无序的打印到 log文件中, 所以很难区分日志是哪个用户的, 可以通过 MDC功能在Filter中为每个登陆用户的线程设置绑定的用户, 这样可以在 打印日志的时候使用 %x{key} 把线程绑定的用户打印出来。

Log4j2 中也有 MDC&NDC的概念, 只是把这2个概念合并到了一个 Thread Context中。

Fish Tagging 大多数现实中的系统都是支持并发处理的。在大多数的多线程系统中,不同的线程处理不同的用户,Logging很适合跟踪和调试复杂的分布式应用, 一个常见的 区分不同客户端输出日志的方法是为每个客户端单独实例化一个Logger,这样增大了日志的增加和管理的开销。

更轻量化的方式是为从同一个客户端发起的日志请求增加一个唯一标识,就像标记了一条鱼,并一直追踪它的运动。 可以在一个事务或者一个请求中使用一个公共标识来跟踪log事件,我们成为 Fish Tagging。

Log4j2提供了2种方式的 Fish Tagging , Thread Context Map 与Thread Context Stack 。 Thread Context Map 类似于 Map,是key/value 对的方式,可以根据key来查找value值,The Thread Context Stack 是堆栈的方式,可以根据堆栈的顺序和元素值来查找。相对来说,key/value 的方式更加灵活,推荐使用。

例子1:Thread Context Stack

1. ThreadContext.push(UUID.randomUUID().toString());// Add the fishtag; 2.

3. logger.debug(\); 4. . 5. . 6. .

7. logger.debug(\); 8. . 9. .

10. ThreadContext.pop();

例子2: Thread Context Map

1. ThreadContext.put(\, UUID.randomUUID().toString());// Add the fishtag; 2. ThreadContext.put(\, request.getRemoteAddr()); 3. ThreadContext.put(\, session.getAttribute(\)); 4. ThreadContext.put(\, request.getServerName()); 5. .

6. logger.debug(\); 7. . 8. .

9. logger.debug(\); 10. . 11. .

12. ThreadContext.clear();

Thread Context Map 和Thread Context Stack默认使用ThreadLocal 来管理每个线程。 Thread Context Map 也可以使用InheritableThreadLocal 通过设置isThreadContextMapInheritable 属性为 \。当使用这种配置时,Map中的内容将被传递到它的子线程。

getContext() and cloneStack() 方法可以获得Map 和Stack 的拷贝副本。


log4j2中文手册(6).doc 将本文的Word文档下载到电脑 下载失败或者文档不完整,请联系客服人员解决!

下一篇:广场排水方案

相关阅读
本类排行
× 注册会员免费下载(下载后可以自由复制和排版)

马上注册会员

注:下载文档有可能“只有目录或者内容不全”等情况,请下载之前注意辨别,如果您已付费且无法下载或内容有问题,请联系我们协助你处理。
微信: QQ: