给子类的基类日志消息添加前缀

huangapple go评论72阅读模式
英文:

Add a prefix to base class log messages from a child class

问题

我有一个基类(void)方法,用于记录消息。是否可以从子类方法中为该实例添加前缀?

示例:

假设基类记录 result data,我可以让它从子类记录 myPrefix: result data 吗?

我正在使用 slf4j。

英文:

I have a base class (void)method which logs a message. Is it possible to add a prefix for that instance from a child class method?

Example:

let say base class logs result data. Can I make it to log myPrefix: result data from a child class.

I'm using slf4j

答案1

得分: 1



一个可能的解决方案是使用继承,并使父类抽象,强制子类实现一个返回 `myPrefix` 的方法:

**ParentClass**

```java
public abstract class ParentClass {

    public void log(String message) {
        logger.log(getLogMessagePrefix() + message);
    }

    abstract String getLogMessagePrefix();
}

ChildClass

public class ChildClass extends ParentClass {

    public final String LOG_PREFIX = "myPrefix";

    @Override
    String getLogMessagePrefix() {
        return LOG_PREFIX;
    }
}

<details>
<summary>英文:</summary>

One possible solution is to use inheritance and make the parent class abstract forcing the child class to implement a method that will return `myPrefix`:

**ParentClass**

    public abstract class ParentClass {

    public void log(String message) {
        logger.log(getLogMessagePrefix() + message);
    }

    abstract String getLogMessagePrefix(); }


**ChildClass**

    public class ChildClass extends ParentClass {

    public final String LOG_PREFIX = &quot;myPrefix&quot;;

    @Override
    String getLogMessagePrefix() {
        return LOG_PREFIX;
    }}




</details>



huangapple
  • 本文由 发表于 2020年8月15日 09:05:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/63421665.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定