[英]Redirect the output of System.err.println to a file without code change
[英]Replacing System.err.println in quick debug of short code examples
我必須寫一些簡短的代碼示例,而使用IDE則太過花俏了。 我使用Gedit。 出於調試目的,我一直在使用快速方法dbgm
。 一些Google搜索提出了類似的建議:
import java.util.Scanner;
public class Tyle {
public Tyle() {
}
/**
* @param debugmessage
* This method takes any debugmessage and prints the string version
* to System.err.println
*/
private static void dbgm(Object debugmessage) {
System.err.println(debugmessage.toString());
}
/**
* @param number
*/
public static int cube(int i) {
int cube;
cube=i*i*i;
dbgm(cube); //debug message
return cube;
}
public static void main(String [] args){
System.out.print("Enter number: ");
Scanner s = new Scanner(System.in);
int inp = s.nextInt();
Tyle.cube(inp);
s.close();
}
}
這有其優點,我可以搜索dbgm
,而dbgm
任何真正的System.out.println()
調用。
但是我完全不確定使用這樣的方法是否是一種好習慣,尤其是在調試模式下。 我一直在考慮使用類似於泛型的東西,在這里我提供了一種類型,而不僅僅是指定Object
(這很冒險)並依賴於toString()
。
我可以在這個簡單的示例中使用assert
,但是在用戶研究過程中可能會出現更為復雜的情況。 例如, number
是否基於用戶輸入。 在某些情況下,我試圖快速檢查某些參數是否提供了期望值。
有沒有一種方法可以安全地編寫dbgm
方法的變體,使我可以在其中獲得適當的描述符,特別是例如,如果它是一個自定義對象? 我想在某種“生產”環境中繼續重復使用該解決方案。
有沒有正確的方法?
如果您要編寫的代碼示例包含單個Java文件,建議不要使用dbmg
方法,而應顯式使用System.our/System.err
打印方法。 使用自定義日志記錄抽象可能會使示例代碼復雜化並包含不必要的細節。
但是,如果:
然后不要重新發明輪子,使用Logging框架。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.