導航:首頁 > 編程語言 > java輸出log文件

java輸出log文件

發布時間:2022-04-21 08:59:30

java列印日誌的幾種方式

在Java 中實現記錄日誌的方式有很多種, 下面給你簡單介紹四種:

  1. 最簡單的方式,就是system.println.out(error) ,這樣直接在控制台列印消息了。

  2. Java.util.logging ; 在JDK 1.4 版本之後,提供了日誌的API ,可以往文件中寫日誌了。

  3. log4j , 最強大的記錄日誌的方式。 可以通過配置 .properties 或是 .xml 的文件, 配置日誌的目的地,格式等等。

  4. commons-logging, 最綜合和常見的日誌記錄方式, 經常是和log4j 結合起來使用。

㈡ java中讀入和輸出文本文件

/**
*測試3:從文本文件中讀取數據
*/
staticvoidtestExample03(){
//1、在內存中打開要讀取文件的字元流對象
try{
Readerreader=newFileReader("e:/ReadMe.log");
//2、從字元流中讀取數據
//一次讀取一個字元(麻煩)
/*intnum=reader.read();
System.out.println((char)num);
num=reader.read();
System.out.println((char)num);*/
//一次讀取一個數組(必須確定數組的長度)
/*char[]cbuf=newchar[10];
reader.read(cbuf);
System.out.println(newString(cbuf));*/
//循環讀取,一次就讀一個
intch=reader.read();
StringBufferbuffer=newStringBuffer();
while(ch!=-1){//讀取成功
buffer.append((char)ch);
ch=reader.read();
}
System.out.println(buffer.toString());
//3、關閉流
reader.close();
}catch(FileNotFoundExceptione){
System.out.println("要讀取的文件不存在:"+e.getMessage());
}catch(IOExceptione){
System.out.println("文件讀取錯誤:"+e.getMessage());
}
}
/**
*測試4:向文本文件中寫入數據
*/
staticvoidtestExample04(){
System.out.println("請輸入內容:");
Stringtext=input.next();
try{
//1、打開流
Writerw=newFileWriter("e:/測試.txt",true);
//2、寫入內容
w.write(text);
//3、關閉流
w.close();
}catch(IOExceptione){
System.out.println("文件寫入錯誤:"+e.getMessage());
}
}
/**
*測試5:使用效率高的字元流讀寫數據
*/
staticvoidtestExample05(){
try{
//1、創建流對象
Readerreader=newFileReader("e:/ReadMe.log");
//構建高效流對象
BufferedReaderbuffReader=newBufferedReader(reader);

//2、讀取一行字元串
Stringline=buffReader.readLine();
StringBufferbuffer=newStringBuffer();
while(line!=null){
buffer.append(line+" ");
line=buffReader.readLine();
}
System.out.println(buffer.toString());;
//3、關閉流
buffReader.close();
reader.close();

Writerw=newFileWriter("e:/NewReadMe.txt");
BufferedWriterbuffWriter=newBufferedWriter(w);

buffWriter.write(buffer.toString());

buffWriter.close();
w.close();
System.out.println("寫入成功!");

}catch(FileNotFoundExceptione){
System.out.println("要讀取的文件不存在:"+e.getMessage());
}catch(IOExceptione){
System.out.println("文件讀取錯誤:"+e.getMessage());
}
}

㈢ java中log和system區別

log是用來打日誌的,system功能就多了,如取系統的時間等等

㈣ 如何查看log日誌文件呢

查看方法:
一、在 Java 與 C 語言中輸出日誌:
1) Java 代碼在程序中輸出日誌, 使用 android.util.Log 類的以下 5 個方法:
Log.v()、Log.d()、Log.i()、Log.w()、Log.e()。
分對應 Verbose、Debug、INFO、Warn、Error 的首字母。
例如:Log.i( "類::函數名", "日期_時間_源碼文件名_行號_日誌信息內容" );
2) C 代碼在程序中輸出日誌,使用 log 的 API 函數:
__android_log_write( 日誌類型宏,日誌標簽字元串,日誌令牌內容字元串 );
需要:1. Android.mk 中添加 LOCAL_LDLIBS := -L$(SYSROOT)/usr/lib -llog
2. *.c 中添加 #include <android/log.h>
3. 日誌類型宏有:

復制代碼 代碼如下:

// Android log priority values, in ascending priority order.
typedef enum android_LogPriority {
ANDROID_LOG_UNKNOWN = 0,
// only for SetMinPriority()
ANDROID_LOG_DEFAULT,
ANDROID_LOG_VERBOSE,
ANDROID_LOG_DEBUG,
ANDROID_LOG_INFO,
ANDROID_LOG_WARN,
ANDROID_LOG_ERROR,
ANDROID_LOG_FATAL,
// only for SetMinPriority(); must be last
ANDROID_LOG_SILENT,
} android_LogPriority;

二、logcat 使用方法:
Usage: logcat [options] [filterspecs]
用法: logcat [選項] [過濾說明]

options include:
選項包含:
-s Set default filter to silent.
Like specifying filterspec '*:S'
設置默認過濾為無聲的。
像指定過濾說明為 *:S ,見下面 過濾說明 部份詳述

-f <filename> Log to file.
Default to stdout
輸出日誌到文件。
默認為 stdout

-r [<kbytes>] Rotate log every kbytes.
(16 if unspecified).
Requires -f
設置環形日誌緩沖區的kbytes。
默認值為16。
需要和 -f 選項一起使用

-n <count> Sets max number of rotated logs to <count>, default 4
設置環形日誌緩沖區的最大數目,默認值是4,需要和 -r 選項一起使用

-v <format> Sets the log print format, where <format> is one of:
設置 log 的列印格式, 格式有如下主要7種:(不能組合使用)
brief
process
tag
thread
raw
time
threadtime
long
-c clear (flush) the entire log and exit
清除所有 log 並退出

-d mp the log and then exit (don't block)
得到所有log並退出且不阻塞

-t <count> print only the most recent <count> lines (implies -d)
僅列印最近的由參數 count 指出的行數(必然包含 -d)

-g get the size of the log's ring buffer and exit
得到環形緩沖區的大小並退出

-b <buffer> Request alternate ring buffer, 'main', 'system', 'radio' or 'events'.
Multiple -b parameters are allowed and the results are interleaved.
The default is -b main -b system.
請求供替換的環形緩沖區,如:main,system,radio,events。
多個 -b 參數是被允許,並且結果是交錯輸出的。
-b main -b system 是默認的。

-B output the log in binary
輸出 log 到二進制文件中。

filterspecs are a series of <tag>[:priority]
過濾說明是一系列 <tag>[:priority]
where <tag> is a log component tag (or * for all) and priority is:
tag 是 eclipse 中 logcat 圖形界面中 Tag 的內容(或者有 * 表示全部),它之後的冒號(:)後面跟優先順序:
日誌類型標識符(優先順序由低到高排列):
1. V — Verbose 詳細的 <- 最低優先權
2. D — Debug 調試
3. I — Info 消息
4. W — Warn 警告
5. E — Error 錯誤
6. F — Fatal 致命的
7. S — Silent 無聲的 <- 最高優先權
'*' means '*:d' and <tag> by itself means <tag>:v
* 意味著 *:d 且 單孤地 tag 意味著 tag:V
If not specified on the commandline, filterspec is set from ANDROID_LOG_TAGS.
如果在命令行上沒有詳細說明,過濾規格即是 ANDROID_LOG_TAGS 結果集。
If no filterspec is found, filter defaults to '*:I'
如果沒有過濾說明,過濾規格默認為 *:I
If not specified with -v, format is set from ANDROID_PRINTF_LOG or defaults to "brief"
如果沒有 -v 指定格式,將是 ANDROID_PRINTF_LOG 或 brief 格式集。
1) 只輸出指定 標簽 和 類型 的日誌
格式:
adb logcat <日誌標簽>:<日誌類型標識符> <日誌標簽>:<日誌類型標識符> ... *:S
註:1. 可以寫多個 <日誌標簽>:<日誌類型標識符> 之間用空格分隔;
2. 最後必須是 *:S ,表示其它的都不要顯示出來
例如:
$ adb logcat dalvikvm:D Checkin:W *:S

註:adb logcat Checkin *:S =等同於=> adb logcat Checkin:V *:S
註:以上命令均沒加 -v 來指出日誌格式,即默認為: ANDROID_PRINTF_LOG 或 brief 格式集。
2) 輸出指定 標簽 和 類型 的帶有格式的日誌
註:以下測試日誌內容為:test log format,
即 eclipse 中的 logcat 圖形界面里的 Text 中的內容!
1. brief - 日誌類型/日誌標簽(進程ID): 日誌內容
例如:$ adb logcat -v brief Checkin *:S
I/Checkin(24713): test log format

2. process - 日誌類型(進程ID) 日誌內容 (日誌標簽)
例如:$ adb logcat -v process Checkin *:S
I(24713) test log format (Checkin)

3. tag - 日誌類型/日誌標簽: 日誌內容
例如:$ adb logcat -v tag Checkin *:S
I/Checkin: test log format

4. thread - 日誌類型(進程ID:線程ID)
例如:$ adb logcat -v thread Checkin *:S
I(24713:0x6089) test log format

5. raw - 日誌內容
例如:$ adb logcat -v raw Checkin *:S
test log format

6. time - 日期 調用時間 日誌類型/日誌標簽(進程ID): 日誌內容
例如:$ adb logcat -v time Checkin *:S
05-27 11:25:33.854 I/Checkin(24713): test log format
7. threadtime - 日期 調用時間 進程ID 線程ID 日誌類型 日誌標簽: 日誌內容
例如:$ adb logcat -v time Checkin *:S
05-27 11:25:33.854 24713 24713 I Checkin: test log format
註:只有此種格式時 線程ID 為十進制數。

8. long - [ 日期 調用時間 進程ID:線程ID 日誌類型/日誌標簽 ] 轉行顯示 日誌內容
例如:$ adb logcat -v long Checkin *:S
[ 05-27 11:25:33.854 24713:0x6089 I/Checkin ]
test log format

㈤ java 如何輸出多個log文件

你可以用多線程,然後使用數據共享,建議你的代碼這樣寫:

synchronized(this)
{
//TODO你的處理代碼
}

這樣至少可以保證你的數據共享同步化安全,但是有可能影響效率

㈥ java log日誌的問題

首先,配置成每天生成的話,.log文件的路徑是不會改變的,比如,日誌文件是log.log,那麼這個文件在第二天會被備份為2013-01-07.log,但是同時會再生成一個log.log文件,所以不會影響你的路徑
其次,如果這個日誌文件一直被系統在添加日誌的話,那麼該文件應該是被加鎖的,其他程序只能讀不能修改和刪除,所以如果該情況下你一定要隔幾天清空一次,一是修改生成日誌的系統,讓其定時清除日誌文件內容,二是寫腳本或程序,先停掉系統,再清空日誌,然後重啟系統。這種方法,不建議採用。
強烈建議,採用第一種方法,然後修改你的讀取日誌的程序,每天讀取一下前一天生成的日誌文件內容就可以了,因為備份文件是用日期命名的,利用這個規律,很容易就可以獲取到要讀取的文件名了

㈦ java重定向標准輸出流到當前目錄的log.txt文件,並輸出如下語句:

packagecom.kidd.atmtest;

importjava.io.FileNotFoundException;
importjava.io.PrintStream;
importjava.text.SimpleDateFormat;
importjava.util.Date;

publicclassTest{

publicstaticvoidmain(String[]args)throwsFileNotFoundException{
System.out.println("log.txt文件位置:"
+Thread.currentThread().getContextClassLoader()
.getResource("log.txt").getFile());
System.setOut(newPrintStream(Thread.currentThread()
.getContextClassLoader().getResource("log.txt").getFile()));
System.out.println("Thisisalogfile.");
System.out
.println("****************************************************");
System.out.println("Time:"
+newSimpleDateFormat("yyyy.MM.ddHH:mm:ss")
.format(newDate()));
System.out.println("Nowsystemisrunningwell.");
System.out.println("MynameisTest.");
}

}

㈧ java 創建一個log日誌

這是以前在網上看到關於處理log日誌的一段代碼,一起學習吧。
至於存到資料庫,那就得再打開log日誌找到所需要的信息做操作了。
importjava.util.logging.*;
importjava.io.*;
publicclassMemoryHandlerTest{
FileHandlerfhandler;
Loggerlogger;
MemoryHandlermhandler;
MemoryHandlerTest(){
try{
fhandler=newFileHandler("my.log");
intnumRec=5;
mhandler=newMemoryHandler(fhandler,numRec,Level.OFF);
logger=Logger.getLogger("com.mycompany");
logger.addHandler(mhandler);
}catch(IOExceptione){
}
}
publicstaticvoidmain(Stringargs[]){
MemoryHandlerTestmt=newMemoryHandlerTest();
inttrigger=(int)(Math.random()*100);
for(inti=1;i<100;i++){
mt.logger.log(Level.INFO,"日誌記錄"+i);
if(i==trigger){
mt.mhandler.push();
break;
}
}
}
}

㈨ 如何在java程序中打log

Java的Log是一個非常強大的寫日誌的工具包,程序員可以隨時把一些想要記錄的信息輸出到本地文件,可以用於觀察程序運行狀況等,代碼如下:
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.Level;
import org.apache.log4j.SimpleLayout;
public class ApacheLog {
public static void main(String args[]) {
Logger logger = Logger.getLogger(ApacheLog.class);
SimpleLayout layout = new SimpleLayout();
FileAppender appender = null;
try {
appender = new FileAppender(layout, "myApacheLog.log", false);
} catch (Exception e) {
}
logger.addAppender(appender);
// Set the logger level to Level.INFO
logger.setLevel(Level.INFO);
// This request will be disabled since Level.DEBUG < Level.INFO.
logger.debug("This is debug.");
// These requests will be enabled.
logger.info("This is an info.");
logger.warn("This is a warning.");
logger.error("This is an error.");
logger.fatal("This is a fatal error.");
}
}

閱讀全文

與java輸出log文件相關的資料

熱點內容
單片機kill4軟體下載收費嗎 瀏覽:846
蘋果手機怎麼連接RMS伺服器 瀏覽:603
cisco路由器基本配置命令 瀏覽:186
android狀態欄顏色透明 瀏覽:116
db2編譯工具 瀏覽:181
騰訊雲伺服器創建環境 瀏覽:567
監管資金怎麼解壓 瀏覽:671
榮耀手機內存清理文件夾 瀏覽:175
外派程序員方案 瀏覽:554
安卓怎麼把桌面的軟體變成卡通 瀏覽:885
魯班鎖解壓嗎 瀏覽:395
打包發送文件如何加密 瀏覽:213
centos解壓縮zip 瀏覽:388
我的世界怎麼用命令風塊取消指令 瀏覽:1000
安卓軟體請求超時怎麼辦 瀏覽:476
androidapp調用另一個app 瀏覽:621
數控銑床法蘭克子程序編程 瀏覽:174
linux打包命令targz 瀏覽:997
抖音app是哪個 瀏覽:407
蘋果app怎麼上架 瀏覽:255