在akka中如何使用log
akka中显示日志不需要第三方jar, 直接使用akka的Logging即可, Logging默认是输出到STDOUT, 当然你也可以使用第三方插件如SLF4J来记录日志, Logging使用的异步方式以此来达到最小的性能损耗.
代码中使用Logging
import akka.actor.*;
import akka.event.Logging;
import akka.event.LoggingAdapter;
class MyActor extends UntypedActor {
LoggingAdapter log = Logging.getLogger(getContext().system(), this);
@Override
public void preStart() {
log.debug("Starting");
}
@Override
public void preRestart(Throwable reason, Option<Object> message) {
log.error(reason, "Restarting due to [{}] when processing [{}]",
reason.getMessage(), message.isDefined() ? message.get() : "");
}
public void onReceive(Object message) {
if (message.equals("test")) {
log.info("Received test");
} else {
log.warning("Received unknown message: {}", message);
}
} }
Dead letters的log
akka中默认dead letters会以info的形式输出.你可以调整显示多少dead letter, 并在之后就不再显示这些log. 另外在程序shutdown时显示相应的dead letters.
akka {
log-dead-letters = 10
log-dead-letters-during-shutdown = on
}
调整logging的级别
akka {
loglevel = "DEBUG"
}
启动时显示相应的config
akka {
# Log the complete configuration at INFO level when the actor system is started.
# This is useful when you are uncertain of what configuration is used.
log-config-on-start = on
}
如果希望非常详细的显示所有接受到的消息
akka {
actor {
debug {
# enable DEBUG logging of all AutoReceiveMessages (Kill, PoisonPill et.c.)
autoreceive = on
}
}
}
使用SLF4J
maven中新增配置
<dependency> <groupId>com.typesafe.akka</groupId> <artifactId>akka-slf4j_2.11</artifactId> <version>2.4.17</version> </dependency> <!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-core -->
ch.qos.logback logback-core 1.1.7 ch.qos.logback logback-classic 1.1.7 resources/目录下新增logback.xml
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>logs\akka.%d{yyyy-MM-dd}.%i.log</fileNamePattern> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>50MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> </rollingPolicy> </appender> <!-- 控制台输出 --> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <!-- 日志输出编码 --> <Encoding>UTF-8</Encoding> <layout class="ch.qos.logback.classic.PatternLayout"> <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符--> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern> </layout> </appender> <root level="DEBUG"> <appender-ref ref="FILE" /> <appender-ref ref="STDOUT"/> </root>
程序中使用
private Logger log = LoggerFactory.getLogger(XXX.class);