经过两天与log4j2的战斗,冬眠和春季,我终于让JPAAppender工作了。

我遵循以下示例:http://logging.apache.org/log4j/2.x/manual/appenders.html#JPAAppender

示例中的类创建具有以下结构的表:

CREATE TABLE `applicationLog` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `wrappedEvent` tinyblob,
  PRIMARY KEY (`id`)
)


第一个问题是我无法记录任何内容,因为tinyblob太小了。我通过将tinyblob更改为largeblob手动修复了此问题。

第一个问题:有没有办法使扩展BasicLogEventEntity的类自己创建一个大对象?

第二个问题:如何使用mysql客户端读取wrappedEvent?如何从日志中删除日志的纯文本?

谢谢

最佳答案

因此,我按如下所示更改了实体,现在db中的blob始终为空(我不再需要它),其他列中填充了可读信息。这只是一个解决方法,但这是我能想到的最好的方法...

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.appender.db.jpa.BasicLogEventEntity;
import org.hibernate.annotations.Type;

/**
 *
 * @author syco
 */
@Entity(name = "applicationLog")
@Table(name = "`applicationLog`")
public class ApplicationLog extends BasicLogEventEntity {

  @Getter
  @Setter
  @Column(name = "`customEventDate`")
  private LocalDateTime customEventDate;

  @Getter
  @Setter
  @Column(name = "`customException`")
  @Type(type = "text")
  private String customException;

  @Getter
  @Setter
  @Column(name = "`customLevel`", length = 512)
  private String customLevel;

  @Getter
  @Setter
  @Column(name = "`customLogger`", length = 512)
  private String customLogger;

  @Getter
  @Setter
  @Column(name = "`customMessage`")
  @Type(type = "text")
  private String customMessage;

  @Getter
  @Setter
  @Column(name = "`customThreadName`", length = 512)
  private String customThreadName;

  @Getter
  @Setter
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "`id`")
  private long id;

  public ApplicationLog() {
    super();
  }

  public ApplicationLog(LogEvent logEvent) {
    super();
    if (logEvent != null) {
      setCustomEventDate(Instant.ofEpochMilli(logEvent.getTimeMillis()).atZone(ZoneId.systemDefault()).toLocalDateTime());
      if (logEvent.getThrown() != null) {
        setCustomException(ExceptionUtils.getStackTrace(logEvent.getThrown()));
      }
      if (logEvent.getLevel() != null) {
        setCustomLevel(logEvent.getLevel().name());
      }
      setCustomLogger(logEvent.getLoggerName());
      if (logEvent.getMessage() != null) {
        setCustomMessage(logEvent.getMessage().toString());
      }
      setCustomThreadName(logEvent.getThreadName());
    }
  }
}

10-07 23:50