maven配置简单的log模块-超越昨天的自己系列(4)
超越昨天的自己系列(4)
用maven构建项目优点太多了,强烈建议项目初期构建使用maven。log模块是项目中必不可少的。一个个模块拼接起来,慢慢学习更方便的构建一个完整,牛逼的项目。
通过这样的命令,会自动创建一个项目:
mvn archetype:create -DgroupId=com.oreilly -DartifactId=my-app
产生类似这样一个项目目录:
推荐:在pom.xml写依赖的时候可以通过下面这个网站来查询:
pom.xml的配置如下:
<project xmlns ="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0 </modelVersion> <groupId>com.kkk.wap </groupId> <artifactId>testapp</artifactId> <version>1.0-SNAPSHOT </version> <packaging>jar </packaging> <name>testapp</name> <url>http://maven.apache.org </url> <properties> <project.build.sourceEncoding> UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.0.13</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> </project>
在项目根目录执行:mvn install 命令
会下载一下jar包:
测试类:
/** * Hello world! * */ public class App { private static Logger logger = LoggerFactory .getLogger ( App. class ); public static void main ( String [] args ){ logger .info ( "App said:show me the money!") ; System .out . println( "Hello World!" ) ; logger .info ( "you said:yo!yo!") ; try { String s = "12w" ; Integer .parseInt ( s) ; } catch (Exception e) { logger .error ( "you have a big poblem:" + e ) ; } } }
logback.xml的配置:
<? xml version ="1.0" encoding= "UTF-8" ?> <!-- Logback Configuration. --> <configuration debug = "false"> <appender name ="AllLOG" class ="ch.qos.logback.core.rolling.RollingFileAppender" > <file> d:/allLog.log</file> <encoding> UTF-8</encoding> <rollingPolicy class ="ch.qos.logback.core.rolling.TimeBasedRollingPolicy" > <FileNamePattern> d:/allLog.%d{yyyy-MM- dd}.log </FileNamePattern> </rollingPolicy> <append> true</append> <layout class ="ch.qos.logback.classic.PatternLayout" > <pattern> <![CDATA[ %n%-4r [%d{yyyy-MM-dd HH:mm:ss} %X{productionMode}] - %X{method} %X{requestURIWithQueryString} [ip=%X{remoteAddr}, ref=%X{referrer}, ua=%X{userAgent}, sid=%X{cookie.JSESSIONID}]%n %-5level %logger{35} - %m%n ]]> </pattern> </layout> </appender> <root> <level value = "info" /> <appender-ref ref = "AllLOG" /> </root> </configuration>
解释一下:日志打在d盘的allLog文件夹下,每一天打完日志他会修改自己名字为d:/allLog.%d{yyyy-MM- dd}.log 这样的格式。注意正在打的日志是在allLog.log里。
关于logback.xml配置可以参考博文:
log输出结果:
419 [2013-06-07 16:02:22 ] - [ip=, ref=, ua=, sid=] INFO com.kkk.wap.App - App said:show me the money! 434 [2013-06-07 16:02:22 ] - [ip=, ref=, ua=, sid=] INFO com.kkk.wap.App - you said:yo!yo! 435 [2013-06-07 16:02:22 ] - [ip=, ref=, ua=, sid=] ERROR com.kkk.wap.App - you have a big poblem:java.lang.NumberFormatException: For input string: "12w"