Java log example

  1. Logrecord filter

import java.util.logging.Filter;

import java.util.logging.Level;

import java.util.logging.LogRecord;

import java.util.logging.Logger;

public class SimpleFilter {

private static Logger logger = Logger.getLogger("SimpleFilter");

static class Duck {

};

static class Wombat {

};

static void sendLogMessages() {

logger.log(Level.WARNING, "Aduck in the house!", new Duck());

logger.log(Level.WARNING, "A Wombat at large!", newWombat());

}

public static void main(String[] args) {

sendLogMessages();

logger.setFilter(newFilter() {

public boolean isLoggable(LogRecord record){

Object[] params = record.getParameters();

if (params == null)

return true; // No parameters

if (record.getParameters()[0]instanceof Duck)

return true; // Only log Ducks

return false;

}

});

logger.info("After setting filter..");

sendLogMessages();

}

}

Output:

Aug 28,2013 11:46:04 AM SimpleFilter sendLogMessages

WARNING:A duck in the house!

Aug 28,2013 11:46:04 AM SimpleFilter sendLogMessages

WARNING:A Wombat at large!

Aug 28,2013 11:46:04 AM SimpleFilter main

INFO:After setting filter..

Aug 28,2013 11:46:04 AM SimpleFilter sendLogMessages

WARNING:A duck in the house!

注:重写isLoggable方法可以对logrecord对象进行过滤。

2. Simple for Formatter Example

import java.util.logging.ConsoleHandler;

import java.util.logging.Formatter;

import java.util.logging.Handler;

import java.util.logging.LogRecord;

import java.util.logging.Logger;

public class SimpleFormatterExample {

private static Logger logger = Logger.getLogger("SimpleFormatterExample");

private static void logMessages() {

logger.info("Line One");

logger.info("Line Two");

}

public static void main(String[] args) {

logger.setUseParentHandlers(false);

Handler conHdlr = new ConsoleHandler();

conHdlr.setFormatter(new Formatter() {

public String format(LogRecord record) {

return record.getLevel() + "  : "

+ record.getSourceClassName() + " -:- "

+ record.getSourceMethodName() + " -:- "

+ record.getMessage() + "\n";

}

});

logger.addHandler(conHdlr);

logMessages();

}

}

Output:

INFO  : SimpleFormatterExample -:- logMessages -:- Line One

INFO  : SimpleFormatterExample -:- logMessages -:- Line Two

注:可以对输出的log格式进行特定格式化。

3. Format log output by overriding tostring()function,

import java.util.logging.Level;

import java.util.logging.LogRecord;

public class PrintableLogRecord extends LogRecord {

public PrintableLogRecord(Level level, String str) {

super(level, str);

}

public StringtoString() {

String result = "Level<" + getLevel() + ">\n" + "LoggerName<"

+ getLoggerName() + ">\n" + "Message<" + getMessage() + ">\n"

+ "CurrentMillis<" + getMillis() + ">\n" + "Params";

Object[] objParams = getParameters();

if (objParams == null)

result += "<null>\n";

else

for (int i =0; i < objParams.length; i++)

result += "  Param # <" + i + " value "

+ objParams[i].toString() + ">\n";

result += "ResourceBundle<" + getResourceBundle()

+ ">\nResourceBundleName<" + getResourceBundleName()

+ ">\nSequenceNumber<" + getSequenceNumber()

+ ">\nSourceClassName<" + getSourceClassName()

+ ">\nSourceMethodName<" + getSourceMethodName()

+ ">\nThreadId<" + getThreadID() + ">\nThrown<" +getThrown()

+ ">";

return result;

}

public static void main(String[] args) {

PrintableLogRecord logRecord = new PrintableLogRecord(Level.FINEST,

"SimpleLog Record");

System.out.println(logRecord);

}

}

Output:

Level<FINEST>

LoggerName<null>

Message<SimpleLog Record>

CurrentMillis<1377662640451>

Params<null>

ResourceBundle<null>

ResourceBundleName<null>

SequenceNumber<0>

SourceClassName<null>

SourceMethodName<null>

ThreadId<10>

Thrown<null>

4.  email log

].equals(; i < toAddr.length; i++)
        to[i] = new InternetAddress(toAddr[i]);
      mimeMsg.setRecipients(Message.RecipientType.TO,to);
      mimeMsg.setSubject(subject);
      mimeMsg.setText(message);
      Transport.send(mimeMsg);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
}

Java log code example的更多相关文章

  1. Java Log Viewer日志查看器

    工欲善其事必先利其器 在投奔怒海--一个Domino老程序猿眼里的Java开发我提到眼下所做的Java开发中遇到的大量日志之问题. server控制台刷屏似地滚动,日志文件飞快地增长,debug的时候 ...

  2. Artistic Style 3.1 A Free, Fast, and Small Automatic Formatter for C, C++, C++/CLI, Objective‑C, C#, and Java Source Code

    Artistic Style - Index http://astyle.sourceforge.net/ Artistic Style 3.1 A Free, Fast, and Small Aut ...

  3. Java相关|Code Review Checklist(Server)

    安全 所有入参均经过校验,包括验证参数数据类型.范围.长度,尽可能采用白名单形式验证所有的输入.对于非法请求,记录WARN log.参考Input Validation Cheat Sheet:前后端 ...

  4. java log日志的输出。

    在Spring框架中添加日志功能: pom.xml <dependency> <groupId>log4j</groupId> <artifactId> ...

  5. ndk-gdb 对java/native code联合调试(升级版)

    之前写过一篇 关于android native 开发,调试的文章(http://www.cnblogs.com/yaozhongxiao/archive/2012/03/13/2393959.html ...

  6. Effective Java提升Code Coverage代码涵盖率 - 就是爱Java

    虽然我们已经有了测试程序,但是如何得知是否已完整测试了主程序?,透过Code Coverage代码涵盖率,我们可以快速地得知,目前系统中,有多少程序中被测试过,不考虑成本跟投资效益比,涵盖率越高,代表 ...

  7. java Log日志规范

    Overview 一个在生产环境里运行的程序如果没有日志是很让维护者提心吊胆的,有太多杂乱又无意义的日志也是令人伤神.程序出现问题时候,从日志里如果发现不了问题可能的原因是很令人受挫的.本文想讨论的是 ...

  8. 西交利物浦大学Java PAPER CODE: CSE105/12-13/S1/Resit Coursework

    Question 6:What is an accessor method?What is a mutator method? 答案参考:http://www.xmsydw.com Number An ...

  9. [转]JetBrains IntelliJ IDEA 13 Keygen (Java Source Code)

    转载:http://www.rover12421.com/2013/12/09/jetbrains-intellij-idea-13-keygen-java-source-code.html JetB ...

随机推荐

  1. hihocoder 1228 Mission Impossible 6

    题意:一个模拟……大概就是模拟一个编辑文档的过程……具体的还是读题吧…… 解法:刚开场就发现的一个模拟……果断敲起来…… 要注意几点与实际编辑过程不同: 1.当用C操作标记一段字符后,只有D会改变这段 ...

  2. [Everyday Mathematics]20150202

    设 $f:\bbR^2\to \bbR$ 为连续函数, 且满足条件 $$\bex f(x+1,y)=f(x,y+1)=f(x,y),\quad\forall\ (x,y)\in \bbR^2. \ee ...

  3. Most Powerful(ZOJ 3471状压dp)

    题意:n个原子,两两相撞其中一个消失,产生能量,给出任意两原子相撞能产生的能量,求能产生的最大能量. 分析:dp[i]表示情况为i时产生的最大能量 /*#include <map> #in ...

  4. const 常量数据,只读

    网上其他的博客地址:1 http://www.cnblogs.com/ronny/p/3672501.html 2 http://www.cnblogs.com/hellogiser/p/cplusp ...

  5. 你今天Python了吗?(上)

    你今天Python了吗?为了提高你的生产效率,赶快去关注一下小蟒蛇的成长吧!别再把Python当作你的业余爱好了,她能为你做手头上几乎所有的工作,而且能做得更好,也让你把写代码看成是一种真正的乐趣.为 ...

  6. CSAPP(1):数字的计算机表示——课后题

    2.65 int even_ones(unsigned x) 要求:return 1 when x contains an even number of 1s; 0 otherwise. 假设int ...

  7. bzoj 2599 [IOI2011]Race (点分治)

    [题意] 问树中长为k的路径中包含边数最少的路径所包含的边数. [思路] 统计经过根的路径.假设当前枚举到根的第S个子树,若x属于S子树,则有: ans<-dep[x]+min{ dep[y] ...

  8. c++ 概念及学习/c++ concept&learning(三)

    这一篇继续说说程序设计中的基本语句:控制块 一 if类控制语句 if if else if  , else if ,else if(条件语句){如果条件为真,要做的一些事情}  if(条件语句) {如 ...

  9. Asmack离线消息时间获取

    DelayInformation info = (DelayInformation)message.getExtension("x","jabber:x:delay&qu ...

  10. the application could not be verified

    在iphone上安装app时,提示the application could not be verified 解决方式: 将iphone已有的这个app卸载,然后安装就可以了.