Skip to content

Instantly share code, notes, and snippets.

@robshep
Last active May 10, 2018 14:07
Show Gist options
  • Save robshep/918c9b6eb95fd740f11891e3a2ebc9ad to your computer and use it in GitHub Desktop.
Save robshep/918c9b6eb95fd740f11891e3a2ebc9ad to your computer and use it in GitHub Desktop.
Logging Logback-access messages via another logger
package net._95point2.common.logging;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import ch.qos.logback.access.spi.IAccessEvent;
import ch.qos.logback.core.OutputStreamAppender;
import ch.qos.logback.core.encoder.Encoder;
import ch.qos.logback.core.encoder.LayoutWrappingEncoder;
import ch.qos.logback.core.status.Status;
import ch.qos.logback.core.status.StatusListener;
public abstract class AccessLogToMainLogAppender extends OutputStreamAppender<IAccessEvent> implements StatusListener
{
private Charset charset = Charset.defaultCharset();
public abstract void log(String msg);
public abstract void status(Status status);
@Override
public void start() {
setOutputStream(new FakeStringBufferOutputStream());
super.start();
}
@Override
public void addStatusEvent(Status status) {
status(status);
}
@Override
public void doAppend(IAccessEvent eventObject) {
/* synchronized, and relying on the immediateFlush=true property of the encoder to do:
* 1. write(byte[])
* 2. followed by a flush()
* which gives us a single logging statement from our fake OutputStream
*/
synchronized (this) {
super.doAppend(eventObject);
}
}
@Override
public void setEncoder(Encoder<IAccessEvent> encoder) {
if(encoder instanceof LayoutWrappingEncoder){
LayoutWrappingEncoder<IAccessEvent> lwe = (LayoutWrappingEncoder<IAccessEvent>) encoder;
Charset charset = lwe.getCharset();
if(charset != null){
this.charset = charset;
}
lwe.setImmediateFlush(true);
}
else {
throw new IllegalArgumentException("Only supports Encoders that extend LayoutWrappingEncoder as we need the immediateflush behaviour");
}
super.setEncoder(encoder);
}
public class FakeStringBufferOutputStream extends OutputStream
{
StringBuilder sb = new StringBuilder();
@Override
public void flush() throws IOException {
AccessLogToMainLogAppender.this.log(sb.toString());
sb.delete(0, sb.length());
}
@Override
public void write(byte[] bytes) throws IOException {
sb.append(new String(bytes, AccessLogToMainLogAppender.this.charset));
}
@Override
public void write(int b) throws IOException {
throw new UnsupportedOperationException("Only supports write(byte[] bytes)");
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
throw new UnsupportedOperationException("Only supports write(byte[] bytes)");
}
}
}
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
<configuration>
<appender name="BRIDGE" class="net._95point2.common.logging.LogbackAccessLogAdapter">
<encoder>
<pattern>req=%U%q method=%m user=%u status=%s size=%b time=%D session=%S referer=%header{Referer} browser=%header{User-Agent} ip=%a</pattern>
</encoder>
</appender>
<appender-ref ref="BRIDGE" />
</configuration>
package net._95point2.common.logging;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.qos.logback.access.spi.IAccessEvent;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;
import ch.qos.logback.core.status.Status;
public class LogbackAccessLogAdapter extends AccessLogToMainLogAppender
{
Logger logger = LoggerFactory.getLogger("RequestLog");
@Override
public void log(String msg) {
logger.info(msg);
}
@Override
public void status(Status status) {
logger.error("{}", status, new Throwable());
}
public LogbackAccessLogAdapter() {
addFilter(new Filter<IAccessEvent>() {
@Override
public FilterReply decide(IAccessEvent event) {
if(event.getRequestURI().startsWith("/static")){
return FilterReply.DENY;
}
else {
return FilterReply.NEUTRAL;
}
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment