log4j在javaWeb項目中的使用

来源:http://www.cnblogs.com/teach/archive/2016/07/30/5720187.html
-Advertisement-
Play Games

在前邊的文章中對log4j的配置文件進行了說明,今天介紹如何在普通的javaWeb項目中使用log4j。 在日常的開發過程中,日誌使用的很頻繁,我們可以利用日誌來跟蹤程式的錯誤,程式運行時的輸出參數等,很多情況下可能會使用System.out.println()這個方法,但是還有一種更加簡潔的方式, ...


在前邊的文章中對log4j的配置文件進行了說明,今天介紹如何在普通的javaWeb項目中使用log4j。

在日常的開發過程中,日誌使用的很頻繁,我們可以利用日誌來跟蹤程式的錯誤,程式運行時的輸出參數等,很多情況下可能會使用System.out.println()這個方法,但是還有一種更加簡潔的方式,那就是使用日誌框架,今天就看看log4j這個日誌框架如何在javaWeb的類中使用。

一、log4j的配置文件

我們要使用log4j必須要有log4j的配置文件,前面一篇文章提到,log4j的配置文件格式有兩種,一種是xml的,另一種是properties的,我更傾向於使用後者,這裡也使用後者。配置文件如下,

### set log levels ###  
log4j.rootLogger = info,stdout,D 
##對com.mucfc包下的所有error級別日誌進行輸出
log4j.logger.com.mucfc
=error log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target = System.out log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n log4j.appender.D = org.apache.log4j.DailyRollingFileAppender log4j.appender.D.File = F://logs/log.log log4j.appender.D.Append = false log4j.appender.D.Threshold = DEBUG log4j.appender.D.layout = org.apache.log4j.PatternLayout log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n


從上邊的配置文件可以看到對整個項目來說,日誌界別為info,單獨對com.mucfc包配置了error級別,輸出目的地有兩種:stdout(控制台)、D(文件,輸出日誌最低級別為debug),也就是說如果在類中有logger.debug()、logger.info()、logger.warn()、logger.error()這樣的方法都會輸出,詳見下邊。

二、初始化log4j配置文件

上邊第一步我們配置了log4j配置文件,下邊就是初始化log4j。我們這裡建的是普通的javaWeb項目,且沒有用任何的框架(如,spring,和spring的結合放在下篇中說明),那麼我們要如何在項目剛啟動就載入配置文件呢?我們知道在web項目中有Filter、listener他們都會在項目啟動時進行初始化,Filter是過濾的在這裡不適合,listener是監聽,這裡可以使用listener,另外還有一個用的比較多的,那就是servlet,這個東西我們在開發中用的很多,且可以指定初始化順序,這裡便使用servlet,且指定初始化順序為1,

package com.mucfc;  

import java.io.File;
import java.io.IOException;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.PropertyConfigurator;

/** 
 * Servlet implementation class Log4JInitServlet 
 */  

public class Log4JInitServlet extends HttpServlet {  
    private static final long serialVersionUID = 1L;  

    /** 
     * @see HttpServlet#HttpServlet() 
     */  
    public Log4JInitServlet() {  
        super();  
        // TODO Auto-generated constructor stub  
    }  

    /** 
     * @see Servlet#init(ServletConfig) 
     */  
    public void init(ServletConfig config) throws ServletException {  
        
        
        
        System.out.println("Log4JInitServlet 正在初始化 log4j日誌設置信息");  
        String log4jLocation = config.getInitParameter("log4j-properties-location");  

        ServletContext sc = config.getServletContext();  
        
       String str= (String)sc.getInitParameter("test");
       System.out.println("str:"+str);

        if (log4jLocation == null) {  
            System.err.println("*** 沒有 log4j-properties-location 初始化的文件, 所以使用 BasicConfigurator初始化");  
            BasicConfigurator.configure();  
        } else {  
            String webAppPath = sc.getRealPath("/");  
            String log4jProp = webAppPath + log4jLocation;  
            File yoMamaYesThisSaysYoMama = new File(log4jProp);  
            if (yoMamaYesThisSaysYoMama.exists()) {  
                System.out.println("使用: " + log4jProp+"初始化日誌設置信息");  
                PropertyConfigurator.configure(log4jProp);  
            } else {  
                System.err.println("*** " + log4jProp + " 文件沒有找到, 所以使用 BasicConfigurator初始化");  
                BasicConfigurator.configure();  
            }  
        }  
        super.init(config);  
    }  

    /** 
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 
     */  
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
        // TODO Auto-generated method stub  
    }  

    /** 
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 
     */  
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
        // TODO Auto-generated method stub  
    }  

}

從上面可以看出,此servlet會從servlet的初始化參數中讀取log4j的路徑,然後使用PropertyConfigurator.configure(log4jProp); 進行初始化,下麵是web.xml,

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Log4j</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
   
  </welcome-file-list>
  <servlet>
    <servlet-name>Log4JTestServlet</servlet-name>
    <servlet-class>com.mucfc.Log4JTestServlet</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>Log4JInitServlet</servlet-name>
    <servlet-class>com.mucfc.Log4JInitServlet</servlet-class>
    <init-param>
      <param-name>log4j-properties-location</param-name>
      <param-value>log4j.properties</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
</web-app>

使用了log4j-properties-location參數名,配置的值為log4j.properties,我把配置文件放在了web-cotent下,即根路徑下,

三、測試

我這裡測試使用的是servlet,在請求servlet時調用log4j的日誌輸出功能,

package com.test;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * Servlet implementation class MyFirstTest
 */
public class MyFirstTest extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    
    private Logger logger=Logger.getLogger(this.getClass());
    
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MyFirstTest() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        
        doPost(request,response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        
        logger.info("this is my info message");
        logger.debug("this is my debug message");
        logger.warn("this is my warn message");
        logger.error("this is my error message");
        
    }

}

首先得到一個日誌對象logger,使用的是,Logger logger=Logger.getLogger(this.getClass()),然後調用了debug()、info()、warn()、error()方法,對日誌進行了列印,根據配置文件,會列印出相應日誌,我們這裡整個項目的日誌級別定義的為info,則,info()、warn()、error()這三個方法的內容會列印在控制台。

綜上所述就是在普通的javaWeb項目中使用log4j,下一篇會說明如何在spring的項目中使用。

歡迎指出不正之處

謝謝


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • ArrayList ArrayList myarry = new ArrayList(); myarry.Add(1);//添加元素 myarry.Add(2);//索引也是從零開始 myarry.Add(3); myarry.Add(4); myarry.Add(5); myarry.Insert ...
  • 問題描述: 最近用VS2010連接ORACLE資料庫的時候突然報錯“錯誤 47 存儲區提供程式工廠類型“Oracle.DataAccess.Client.OracleClientFactory”未實現 IServiceProvider 介面。請使用實現該介面的存儲區提供程式。”。某度上面給的解決辦法 ...
  • 火熱的夏季迎了ComponentOne今年的第2個重大發佈。這次發佈包含了一些非常棒的新控制項以及很多大的功能增強。 ...
  • @(Java)[Struts|Interceptor] Struts2 更改校驗配置文件位置 在Struts2中提供的攔截器校驗 ,該校驗器中預設的配置文件位於Action包的位置下,需要和Action類放在一起,而提供的註解又不能針對每個方法不同的參數校驗,只能使用配置文件方式來實現同一個Acti ...
  • 父類: 子類: 輸出: the entrance. test.Child@2a139a55class test.Child call Child1 functiontest.Child@2a139a55class test.Childcall Child1 functionException in ...
  • 我們訪問資源需要關註對資源的鎖定、對資源的申請和釋放,還有考慮可能遇到的各種異常。這些事項本身與代碼的邏輯操作無關,但我們不能遺漏。也就是說進入方法時獲取資源,退出方法時釋放資源。這種處理就進入了Execute Around模式的範疇。 在scala里可以用函數值實現這種模式。下麵是一個示例,使用R... ...
  • 題意不難理解,但是一開始還是沒有看清楚題目。Replace the first occurrence of the find string within the text by the replace-by string, then try to perform the same replaceme ...
  • 一、事務 簡單點說,事務就是一件事情。所有與事務相關的內容都是圍繞這一件事情展開的。 二、事務的特性:ACID A:Atomicity(原子性),事務必須是一個不可分割的整體。 C:Consistency(一致性),執行完資料庫操作後,數據不會被破壞。如:從 A 賬戶轉賬到 B,要保證 A 賬戶扣錢 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...