1. 程式人生 > >java遊戲伺服器開發之三--日誌

java遊戲伺服器開發之三--日誌

        日誌在一個系統中的重要性還是很大的,有時候專案部署到伺服器上,不可能使用斷點除錯的方式,只能從日誌檔案中查詢蛛絲馬跡。

這邊是使用的slf4j。

        在pom檔案中新增slf4j

<!-- 日誌包 -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.13</version>
    </dependency>

        然後再類中使用:

                import org.slf4j.Logger;
		import org.slf4j.LoggerFactory;
		public class Main {
		  private static final Logger logger = LoggerFactory.getLogger(Main.class);


		  public static void main(String[] args) {
			logger.info("HelloWorld");
		  }
		}

        這時候執行應該會出這個問題:

                log4j:WARN No appenders could be found for logger (com.lizhaobolg.Main).
		log4j:WARN Please initialize the log4j system properly.
		log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

        是log的配置檔案沒有設定,我們需要在resource中新增log4j.xml

注意下,這個檔案中的<appender name="file">這個標籤,是列印日誌時,同時生成日誌檔案,配置的時候最好一句話記得加上<appender-ref ref="file" />。

<?xml version="1.0" encoding="UTF-8"?>
		<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">
		<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

			<!-- Appenders -->
			<appender name="console" class="org.apache.log4j.ConsoleAppender">
				<param name="Target" value="System.out" />
				<layout class="org.apache.log4j.PatternLayout">
					<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p %c - %m%n" />
				</layout>
			</appender>

			<appender name="file" class="org.apache.log4j.DailyRollingFileAppender">
				<param name="File" value="logs/server.log" />
				<param name="DatePattern" value="'.'yyyy-MM-dd'.log'" />
				<layout class="org.apache.log4j.PatternLayout">
					<param name="ConversionPattern" value="[%d{yyyy-MM-dd HH:mm:ss.SSS\} %-5p] [%t] %c{3\} - %m%n" />
				</layout>
			</appender>

			<!-- Application Loggers -->
			<logger name="com.fh">
				<level value="info" />
			</logger>

			<!-- 3rdparty Loggers -->
			<logger name="org.springframework.core">
				<level value="info" />
			</logger>

			<logger name="org.springframework.beans">
				<level value="info" />
			</logger>

			<logger name="org.springframework.context">
				<level value="info" />
			</logger>

			<logger name="org.springframework.web">
				<level value="info" />
			</logger>

			<logger name="org.springframework.jdbc">
				<level value="info" />
			</logger>

			<logger name="org.mybatis.spring">
				<level value="info" />
			</logger>
			<logger name="java.sql">
				<level value="info" />
			</logger>
			<logger name="net.sf.ehcache.store.disk.Segment">
				<level value="warn" />
			</logger>
			<!-- Root Logger -->
			<root>
				<priority value="debug" />
				<appender-ref ref="console" />
				<appender-ref ref="file" />
			</root>

		</log4j:configuration>

nice上面的程式碼在碼雲上 https://gitee.com/lizhaoandroid/JgServer
可以加qq群一起探討Java遊戲伺服器開發的相關知識 676231564