Lab4--关于log的使用

日志框架可配置日志记录,在lab4中使用log4j2完成基本日志功能。介绍了log4j2的下载方法,可从Apache官网下载,向项目导入log4j-core和log4j-api的jar包。还说明了配置文件格式,以及在lab4中设置配置文件,展示log和异常配合使用。

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

日志框架提供了包含可配置日志记录的功能,可以在运行时和单个功能部件中启用、禁用或增加详细信息。
在lab4中使用log4j2完成基本日志功能

关于log4j2的下载

Apache官网下载Log4j2,http://logging.apache.org/log4j/2.x/download.html
向项目中导入jar包,基本上只需要导入一下两个包,xx为版本号:
log4j-core-xx.jar
log4j-api-xx.jar
在lab4中使用的版本为log4j2-2.11.2
接下来需要配置文件,与log4j1不同,2的版本中配置文件不能是properties,只能采用.xml、.json或者.jsn格式,以下相当于缺省配置文件

<?xml version="1.0" encoding="UTF-8"?>  
    <configuration status="OFF">  
        <appenders>  
            <Console name="Console" target="SYSTEM_OUT">  
                <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>  
            </Console>  
        </appenders>  
        <loggers>  
            <root level="error">  
                <appender-ref ref="Console"/>  
            </root>  
        </loggers>  
    </configuration>

关于lab4中日志的使用

在lab4中将配置文件设置为如下形式:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
 
        <File name="File" filename="src\log.log"
            filepattern="%d{YYYY-MM-dd HH:mm:ss}-fargo.log">
            <PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss} %l [%t] %-5p %c{1}:%L - %msg%n" />
        </File>
 
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="File" />
        </Root>
    </Loggers>
</Configuration>

以AtomStructure为例展示log和异常的配合使用

package CircularOrbit;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import centralObject.CentralObject;
import exception.AtomNameException;
import exception.AtomTrackNumException;
import exception.AtomTrackNumMatchException;
import exception.ElectronFormatException;
import exception.ElectronNumLabelException;
import exception.StellarTrackRadiusException;
import physicalObject.PhysicalObject;
import track.Track;

public class AtomStructure<L,E> extends ConcreteCircularOrbit<L,E>{
 
 public static Logger logger = LogManager.getLogger(AtomStructure.class.getName());
 @Override
 public void readFile(String filename) throws IOException,AtomNameException, AtomTrackNumException,AtomTrackNumMatchException,ElectronFormatException,ElectronNumLabelException, StellarTrackRadiusException{
  String format1 = "(ElementName ::= )([A-Z][a-z]+)";
  String format2 = "(NumberOfElectron ::= )(\\d+/\\d+;?)+";
  String format3 = "(NumberOfTracks ::= )(\\d+)";
  
  String pathname = "test\\txt\\"+filename;
  Matcher m1,m2,m3;
  String atomName = null;
  int trackNum=0;
  String[]trackNumber = null;
  String[]tracks = null;
  File file = new File(pathname);
  InputStreamReader reader = new InputStreamReader(new FileInputStream(file));
  BufferedReader br = new BufferedReader(reader);
  String line;
  boolean f = false,ff=false,fff=false;
  while((line = br.readLine())!=null) {
   m1 = Pattern.compile(format1).matcher(line);
   m2 = Pattern.compile(format2).matcher(line);
   m3 = Pattern.compile(format3).matcher(line);
   String format4 = "(NumberOfElctron ::= )([\\s\\S]*)";
   Matcher m4 = Pattern.compile(format4).matcher(line);
   while(m1.find()) {
    atomName = m1.group(2);
    
    char[] atomNameChar = atomName.toCharArray();
    if (atomNameChar.length>2||atomNameChar.length<=0||atomNameChar==null) {
     logger.error("异常类型:AtomNameException"+
        "操作错误:AtomName不规范"+
        "停止读取文件");
     throw new AtomNameException("the name of the atom is illegal!");
    }
    if (atomNameChar.length==1) {
     if (!Character.isUpperCase(atomNameChar[0])) {
      logger.error("异常类型:AtomNameException"+
        "操作错误:AtomName不规范"+
        "停止读取文件");
      throw new AtomNameException("the name of the atom's first character is not uppercase");
     }
    }
    if (atomNameChar.length==2) {
     if (!Character.isUpperCase(atomNameChar[0])||!Character.isLowerCase(atomNameChar[1])) {
      logger.error("异常类型:AtomNameException"+
        "操作错误:AtomName不规范"+
        "停止读取文件");
      throw new AtomNameException("the name of the atom's first character should be uppercase and the second one should be lowercase");
     }
    }
    
    f = true;
    CentralObject central = CentralObject.createAtom(atomName);
    super.addCentralObject((L)central);
   }
   while(m3.find()) {
    trackNum = Integer.valueOf(m3.group(2));
     if (trackNum<=0) {
      logger.error("异常类型:AtomTrackNumException"+
        "操作错误:TrackNumber数值不规范"+
        "停止读取文件");
      throw new AtomTrackNumException("the number of tracks is zero!");
     }
    ff = true;
   }
   while(m2.find()) {
    tracks = m2.group().split("NumberOfElectron ::= |;");
    for (int i=1;i<tracks.length;i++) {
     trackNumber = tracks[i].split("/");
     if (trackNumber.length!=2) {
      logger.error("异常类型:ElectronFormatException"+
        "操作错误:电子和轨道的格式不规范"+
        "停止读取文件");
       throw new ElectronFormatException("the electrons on the track should use '/' to split");
     }
     if (trackNumber.length==2) {
      Track t = new Track(Integer.valueOf(trackNumber[0]));
      super.addTrack(t);
      int electronNum = Integer.valueOf(trackNumber[1]);
      for (int j=1;j<=electronNum;j++) {
       PhysicalObject p = PhysicalObject.createElectron();
       super.addPhysicalObject(t, (E)p);
      }
     }
    }
    fff = true;
   }
   
  }
   
  if ((!fff)||(!f)||(!ff)) {
   logger.error("异常类型:ElectronNumLabelException"+
     "操作错误:标签NumberOfElectron或者NumberOfTracks或者ElementName不规范"+
     "停止读取文件");
   throw new ElectronNumLabelException("the label of 'NumberOfElectron ::= ' or 'NumberOfTracks ::= '"
     + " or 'ElementName ::= ' does'n match!");
  }
  if (tracks.length-1 != trackNum) {
   logger.error("异常类型:AtomTrackNumMatchException"+
     "操作错误:输入的TrackNumber和电子所在轨道总和不匹配"+
     "停止读取文件");
   throw new AtomTrackNumMatchException("the number of tracks does'n match!");
  }
  if ((fff)&&(ff)&&(f)) {
    CentralObject central = CentralObject.createAtom(atomName);
    super.addCentralObject((L)central);
  }
  
  
 }
 @Override
 public boolean check() {
  return true;
 }
 @Override
 public int getInfo(E e) {
  throw new UnsupportedOperationException();
 }
}

如此实现每当异常发生时日志有记录。

### Lab-Express 框架概述 Lab-Express 是一种专注于实验和学习目的而设计的 Express.js 扩展框架。此框架旨在简化 Web 应用程序开发过程中的常见任务,提供更简洁的方法来处理路由、中间件和其他 HTTP 请求相关操作[^1]。 ### 安装与配置 为了开始使用 Lab-Express,在命令行工具中执行如下 Git 命令可以获取项目源码: ```bash git clone https://github.com/example/lab-express.git ``` 安装依赖项并启动服务器: ```bash cd lab-express npm install node app.js ``` 上述代码片段展示了如何通过 npm 来管理包以及运行应用程序入口文件 `app.js`[^2]。 ### 路由定义 创建简单的 GET 和 POST 方法对应的 API 接口非常直观。下面是一个基本的例子说明了怎样设置这些接口: ```javascript const express = require('express'); const router = express.Router(); // 处理GET请求 router.get('/', (req, res) => { res.send('Hello World!'); }); // 处理POST请求 router.post('/submit', (req, res) => { const data = req.body; console.log(data); res.status(200).json({ message: 'Data received' }); }); ``` 这段 JavaScript 代码实现了两个 RESTful 风格的服务端点——根路径下的欢迎消息返回服务和 `/submit` 下的数据提交接收服务。 ### 中间件应用 利用内置的支持机制,可以在不改变原有逻辑的情况下轻松集成第三方库作为中间件功能的一部分。比如解析 JSON 格式的请求体内容: ```javascript const bodyParser = require('body-parser'); app.use(bodyParser.json()); ``` 这里引入了一个名为 `bodyParser` 的模块用于自动转换传入的消息主体为易于操作的对象形式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值