- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) >
- 如何配置accesslog以及accesslog 的各種占位符
這期內容當中小編將會(huì )給大家帶來(lái)有關(guān)如何配置accesslog以及accesslog 的各種占位符,文章內容豐富且以專(zhuān)業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
server: undertow: # access log相關(guān)配置 accesslog: # 存放目錄,默認為 logs dir: ./log # 是否開(kāi)啟 enabled: true # 格式,各種占位符后面會(huì )詳細說(shuō)明 pattern: '{ "transportProtocol":"%{TRANSPORT_PROTOCOL}", "scheme":"%{SCHEME}", "protocol":"%{PROTOCOL}", "method":"%{METHOD}", "reqHeaderUserAgent":"%{i,User-Agent}", "cookieUserId": "%{c,userId}", "queryTest": "%{q,test}", "queryString": "%q", "relativePath": "%R, %{REQUEST_PATH}, %{RESOLVED_PATH}", "requestLine": "%r", "uri": "%U", "thread": "%I", "hostPort": "%{HOST_AND_PORT}", "localIp": "%A", "localPort": "%p", "localServerName": "%v", "remoteIp": "%a", "remoteHost": "%h", "bytesSent": "%b", "time":"%{time,yyyy-MM-dd HH:mm:ss.S}", "status":"%s", "reason":"%{RESPONSE_REASON_PHRASE}", "respHeaderUserSession":"%{o,userSession}", "respCookieUserId":"%{resp-cookie,userId}", "timeUsed":"%Dms, %Ts, %{RESPONSE_TIME}ms, %{RESPONSE_TIME_MICROS} us, %{RESPONSE_TIME_NANOS} ns", }' # 文件前綴,默認為 access_log prefix: access. # 文件后綴,默認為 log suffix: log # 是否另起日志文件寫(xiě) access log,默認為 true # 目前只能按照日期進(jìn)行 rotate,一天一個(gè)日志文件 rotate: true
Undertow 的 accesslog 處理核心類(lèi)抽象是 io.undertow.server.handlers.accesslog.AccesslogReceiver
。由于目前 Undertow 的 AccesslogReceiver
只有一種實(shí)現在使用,也就是 io.undertow.server.handlers.accesslog.DefaultAccessLogReceiver
。
查看 DefaultAccessLogReceiver
的 rotate 時(shí)機:
DefaultAccessLogReceiver
/** * 計算 rotate 時(shí)間點(diǎn) */ private void calculateChangeOverPoint() { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.HOUR_OF_DAY, 0); //當前時(shí)間日期 + 1,即下一天 calendar.add(Calendar.DATE, 1); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.US); currentDateString = df.format(new Date()); // if there is an existing default log file, use the date last modified instead of the current date if (Files.exists(defaultLogFile)) { try { currentDateString = df.format(new Date(Files.getLastModifiedTime(defaultLogFile).toMillis())); } catch(IOException e){ // ignore. use the current date if exception happens. } } //rotate 時(shí)機是下一天的 0 點(diǎn) changeOverPoint = calendar.getTimeInMillis(); }
其實(shí) Undertow 中的 accesslog 占位符,就是之前我們提到的 Undertow Listener 解析請求后抽象的 HTTP server exchange 的屬性。
官網(wǎng)文檔的表格并不是最全的,并且注意點(diǎn)并沒(méi)有說(shuō)明,例如某些占位符必須打開(kāi)某些 Undertow 特性才能使用等等。這里我們列出下。
首先先提出一個(gè)注意點(diǎn),參數占位符,例如 %{i,你要看的header值}
查看 header 的某個(gè) key 的值。逗號后面注意不要有空格,因為這個(gè)空格會(huì )算入 key 里面導致拿不到你想要的 key。
注意:
路徑參數 PathVariable 由于并沒(méi)有被 Undertow 的 Listener 或者 Handler 解析處理,所以攔截不到,無(wú)法確認是否是一個(gè) PathVariable 還是就是 url 路徑。所以,PathVariable 的占位符是不會(huì )起作用的。
注意:
請求的遠程地址我們一般不從請求連接獲取,而是通過(guò) Http Header 里面的 X-forwarded-for
或者 X-real-ip
等獲取,因為現在請求都是通過(guò)各種 VPN,器發(fā)上來(lái)的。
注意:默認 undertow 沒(méi)有開(kāi)啟請求時(shí)間內統計,需要打開(kāi)才能統計響應時(shí)間,如何開(kāi)啟呢?通過(guò)注冊一個(gè) WebServerFactoryCustomizer
到 Spring ApplicationContext 中即可。請看下面的代碼(項目地址:https://github.com/HashZhang/spring-cloud-scaffold/blob/master/spring-cloud-iiford/):
spring.factories
(省略無(wú)關(guān)代碼)
# AutoConfiguration org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.github.hashjang.spring.cloud.iiford.service.common.auto.UndertowAutoConfiguration
UndertowAutoConfiguration
//設置proxyBeanMethods=false,因為沒(méi)有 @Bean 的方法互相調用需要每次返回同一個(gè) Bean,沒(méi)必要代理,關(guān)閉增加啟動(dòng)速度 @Configuration(proxyBeanMethods = false) @Import(WebServerConfiguration.class) public class UndertowAutoConfiguration { }
WebServerConfiguration
//設置proxyBeanMethods=false,因為沒(méi)有 @Bean 的方法互相調用需要每次返回同一個(gè) Bean,沒(méi)必要代理,關(guān)閉增加啟動(dòng)速度 @Configuration(proxyBeanMethods = false) public class WebServerConfiguration { @Bean public WebServerFactoryCustomizer<ConfigurableUndertowWebServerFactory> undertowWebServerAccessLogTimingEnabler(ServerProperties serverProperties) { return new DefaultWebServerFactoryCustomizer(serverProperties); } }
DefaultWebServerFactoryCustomizer
public class DefaultWebServerFactoryCustomizer implements WebServerFactoryCustomizer<ConfigurableUndertowWebServerFactory> { private final ServerProperties serverProperties; public DefaultWebServerFactoryCustomizer(ServerProperties serverProperties) { this.serverProperties = serverProperties; } @Override public void customize(ConfigurableUndertowWebServerFactory factory) { String pattern = serverProperties.getUndertow().getAccesslog().getPattern(); // 如果 accesslog 配置中打印了響應時(shí)間,則打開(kāi)記錄請求開(kāi)始時(shí)間配置 if (logRequestProcessingTiming(pattern)) { factory.addBuilderCustomizers(builder -> builder.setServerOption(UndertowOptions.RECORD_REQUEST_START_TIME, true)); } } private boolean logRequestProcessingTiming(String pattern) { if (StringUtils.isBlank(pattern)) { return false; } //判斷 accesslog 是否配置了查看響應時(shí)間 return pattern.contains(ResponseTimeAttribute.RESPONSE_TIME_MICROS) || pattern.contains(ResponseTimeAttribute.RESPONSE_TIME_MILLIS) || pattern.contains(ResponseTimeAttribute.RESPONSE_TIME_NANOS) || pattern.contains(ResponseTimeAttribute.RESPONSE_TIME_MILLIS_SHORT) || pattern.contains(ResponseTimeAttribute.RESPONSE_TIME_SECONDS_SHORT); } }
還有安全相關(guān)的屬性(SSL 相關(guān),登錄認證 Authentication 相關(guān)),微服務(wù)內部調用一般用不到,我們這里就不贅述了。 其它內置的屬性,在 Spring Boot 環(huán)境下一般用不到,我們這里就不討論了。
我們最開(kāi)始配置的 accesslog 的例子請求返回如下( JSON 格式化之后的結果):
{ "transportProtocol": "http/1.1", "scheme": "http", "protocol": "HTTP/1.1", "method": "GET", "reqHeaderUserAgent": "PostmanRuntime/7.26.10", "cookieUserId": "testRequestCookieUserId", "queryTest": "1", "queryString": "?test=1&query=2", "relativePath": "/test, /test, -", "requestLine": "GET /test?test=1&query=2 HTTP/1.1", "uri": "/test", "thread": "XNIO-2 task-1", "hostPort": "127.0.0.1:8102", "localIp": "127.0.0.1", "localPort": "8102", "localServerName": "127.0.0.1", "remoteIp": "127.0.0.1", "remoteHost": "127.0.0.1", "bytesSent": "26", "time": "2021-04-08 00:07:50.410", "status": "200", "reason": "OK", "respHeaderUserSession": "testResponseHeaderUserSession", "respCookieUserId": "testResponseCookieUserId", "timeUsed": "3683ms, 3.683s, 3683ms, 3683149 us, 3683149200 ns", }
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自互聯(lián)網(wǎng)轉載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權請聯(lián)系QQ:712375056 進(jìn)行舉報,并提供相關(guān)證據,一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容。
Copyright ? 2009-2021 56dr.com. All Rights Reserved. 特網(wǎng)科技 特網(wǎng)云 版權所有 珠海市特網(wǎng)科技有限公司 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2
建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站