System.out.print 和 logger 输出日志路径

本文探讨了在项目开发中使用System.out与log4j的不同之处。System.out仅在控制台显示日志,不利于长期跟踪和分析;而log4j能将日志记录到文件中,便于日后查阅和问题定位。文章还分享了一种同时使用System.out和log4j的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一天接触程序就敲出的命令:System.out.print("Hello World"),

后来慢慢的接触到了 log4j,至今为止也一直在使用。

而且在项目中也常常禁止使用 System.out 的方式输出日志,这是为什么呢?

今天做了一个测试:

 System.out. 输出的日志只打印在控制台,而没有存储到一个日志文件中,如果我们在生产环境这样打印出来毫无意义。

但我们的 log4j 是一个实实在在的日志解决方案,通过配置文件,打印出我们需要的日志,便于我们分析、追踪日志信息。后续有时间我会补一篇关于日志的项目,敬请期待。。。

如果既想使用System.out 还想打印出日志,下面有一个简单的方法,提供参考:

@Test
    public void testLog() throws FileNotFoundException {
        System.out.println("这是 System.out 日志");//打印在控制台
        //System.setOut(new PrintStream(new File("C:/projects/demo/trunk/logs/outLog.txt")));
//有朋友发现多次输出日志会覆盖之前日志,特此修正
System.setOut(new PrintStream(new FileOutputStream("C:/projects/demo/dxtp_20181120/trunk/logs/outLog.txt",true),true));
        System.out.println("这是 System.out 日志");//打印在日志文件中
        log.info("这是log日志");
        logBussiness.info("这是 logBussiness日志");
        logDb.info("这是logDb日志");
        logFactory.info("这是logFactory日志");
    }

日志查看如下: 

将下列代码针对jdk1.3进行兼容:import java.lang.String ; import java.io.*; import java.net.*; public class SimpleWebServer { public static void main(String[] args) throws IOException { int port = 8080; ServerSocket serverSocket = new ServerSocket(port); System.out.println("Server started on port " + port); while (true) { Socket clientSocket = serverSocket.accept(); handleRequest(clientSocket); clientSocket.close(); } } private static void handleRequest(Socket clientSocket) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); PrintStream out = new PrintStream(clientSocket.getOutputStream()); String requestLine = in.readLine(); if (requestLine == null) { return; } String[] tokens = requestLine.split(" "); String uri = tokens[1]; System.out.println("uri = " + uri); String fileName = uri.substring(1); System.out.println("FileName: " + fileName); File file = new File(fileName); if (file.exists()) { String contentType = getContentType(file); String response = "HTTP/1.1 200 OK\n" + "MIME-version:1.0" + "\n" + "Content-Type:" + contentType + "\n" + "Content-Length: " + file.length() + "\n" + "\n"; out.print(response); // 将文件内容传送 DataInputStream d = new DataInputStream(new FileInputStream(file)); int len = (int) file.length(); byte[] buf = new byte[len]; d.readFully(buf);//从输入流中读取一些字节,并将它们存储在缓冲区数组 b 中。 out.write(buf, 0, len);//将 len 字节从指定的初始偏移量为off=0的 byte数组写入此流。如果启用自动刷新,则调用 flush 方法 out.flush();//刷新该流的缓冲。 d.close(); out.flush(); } else { String notFound = "<html><head>
最新发布
03-29
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值