In the last section we talked about how to use Undertow As our Web Service container , In this section, we will analyze the use of Undertow Another problem , That's how to configure accesslog, as well as accesslog Various placeholders for .

accesslog Related configuration

server:
undertow:
# access log Related configuration
accesslog:
# Storage directory , The default is logs
dir: ./log
# Open or not
enabled: true
# Format , The various placeholders are described in detail later
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",
}'
# File prefix , The default is access_log
prefix: access.
# file extension , The default is log
suffix: log
# Do you want to write another log file access log, The default is true
# At present, only by date rotate, One log file a day
rotate: true

Be careful 1: Log files rotate At present only by date

Undertow Of accesslog Dealing with core class abstraction is io.undertow.server.handlers.accesslog.AccesslogReceiver. Due to the present Undertow Of AccesslogReceiver Only one implementation is in use , That is to say io.undertow.server.handlers.accesslog.DefaultAccessLogReceiver.

see DefaultAccessLogReceiver Of rotate opportunity :

DefaultAccessLogReceiver

/**
* Calculation rotate Point in time
*/
private void calculateChangeOverPoint() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR_OF_DAY, 0);
// Current time date + 1, The next day
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 The timing is the next day 0 spot
changeOverPoint = calendar.getTimeInMillis();
}

accesslog Place holder

Actually Undertow Medium accesslog Place holder , That's what we mentioned before Undertow Listener After parsing the request, abstract HTTP server exchange Properties of .

Official document It's not the most complete , And note that there's no explanation , For example, some placeholders must open some Undertow Features can be used and so on . Here's a list of .

First of all, I would like to make a point of attention , Parameter placeholder , for example %{i, What you want to see header value } see header One of the key Value . Be careful not to have spaces after commas , Because this space will count key You can't get what you want key.

Request related properties

describe Abbreviation placeholder Full name placeholder Parameter placeholder Source code
Request transport protocol , Equivalent to Request protocol nothing %{TRANSPORT_PROTOCOL} nothing TransportProtocolAttribute
Request mode , for example http、https etc. %{SCHEME} nothing RequestSchemeAttribute
Request protocol , for example HTTP/1.1 etc. %H %{PROTOCOL} nothing RequestProtocolAttribute
Request method , for example GET、POST etc. %m %{METHOD} nothing RequestMethodAttribute
request Header A certain value of nothing nothing %{i, What you want to see header value } RequestHeaderAttribute
Cookie A certain value of nothing nothing %{c, What you want to see cookie value } perhaps %{req-cookie, What you want to see cookie value } They correspond to each other CookieAttribute and RequestCookieAttribute
Path parameter PathVariable Because it has not been Undertow Of Listener perhaps Handler Parsing , So we can't intercept , Can't confirm if it's a PathVariable Or just url route . therefore ,PathVariable It doesn't work . nothing nothing %{p, The path parameters you want to see key } PathParameterAttribute
Request parameters , namely url Of ? After that, the key value pairs , Here you can choose to view a key Value . nothing nothing %{q, The request parameters you want to see key} QueryParameterAttribute
Request parameter string , namely url Of ? All the characters after } %q( It doesn't contain ?) %{QUERY_STRING}( It doesn't contain ?);%{BARE_QUERY_STRING}( contain ?) nothing QueryStringAttribute
Request relative path ( stay Spring Boot In the environment , In most cases RequestPath and RelativePath also ResolvedPath It is equivalent. ), Remove host,port, The path to the request parameter string %R %{RELATIVE_PATH} perhaps %{REQUEST_PATH} perhaps %{RESOLVED_PATH} nothing They correspond to each other RelativePathAttribute and RequestPathAttribute and ResolvedPathAttribute
Request the whole string , Include request methods , Request relative path , Request parameter string , Request protocol , for example Get /test?a=b HTTP/1.1 %r %{REQUEST_LINE} nothing RequestLineAttribute
request URI, Including request relative path , Request parameter string %U %{REQUEST_URL} nothing RequestURLAttribute
The thread that processes the request %I %{THREAD_NAME} nothing ThreadNameAttribute

Be careful :

  1. Path parameter PathVariable Because it has not been Undertow Of Listener perhaps Handler Parsing , So we can't intercept , Can't confirm if it's a PathVariable Or just url route . therefore ,PathVariable It doesn't work .

Request address related

describe Abbreviation placeholder Full name placeholder Parameter placeholder Source code
host and port, It is commonly HTTP request Header Medium Host value , If Host If it is empty, the local address and port will be obtained , If the port is not obtained, the default port will be used according to the protocol (http:80,,https:443) nothing %{HOST_AND_PORT} nothing HostAndPortAttribute
Request local address IP %A %{LOCAL_IP} nothing LocalIPAttribute
Request local port Port %p %{LOCAL_PORT} nothing LocalPortAttribute
Request local host name , It is commonly HTTP request Header Medium Host value , If Host If it is empty, the local address will be obtained %v %{LOCAL_SERVER_NAME} nothing LocalServerNameAttribute
Request remote host name , Get the remote host address through the connection %h %{REMOTE_HOST} nothing RemoteHostAttribute
Request remote IP, Get the remote IP %a %{REMOTE_IP} nothing RemoteIPAttribute

Be careful :

  1. We usually don't get the remote address of the request from the request connection , But through Http Header Inside X-forwarded-for perhaps X-real-ip Etc , Because now requests are made through all kinds of VPN, The load balancer that comes up .

Response related properties

describe Abbreviation placeholder Full name placeholder Parameter placeholder Source code
The size of the number of bytes sent , except Http Header outside %b ( If it's empty, it's -) perhaps %B ( If it's empty, it's 0) %{BYTES_SENT} ( If it's empty, it's 0) nothing BytesSentAttribute
accesslog Time , This is not the time to receive the request , It's the response time %t %{DATE_TIME} %{time, You customize it java in SimpleDateFormat The format of } DateTimeAttribute
HTTP Response status code %s %{RESPONSE_CODE} nothing ResponseCodeAttribute
HTTP Response reason nothing %{RESPONSE_REASON_PHRASE} nothing ResponseReasonPhraseAttribute
Respond to Header A certain value of nothing nothing %{o, What you want to see header value } ResponseHeaderAttribute
Respond to Cookie A certain value of nothing nothing %{resp-cookie, What you want to see cookie value } ResponseCookieAttribute
response time , Default undertow There is no open request time statistics , You need to open it to count the response time %D( millisecond , for example 56 representative 56ms) %T( second , for example 5.067 representative 5.067 second ) %{RESPONSE_TIME}( Equivalent to %D) %{RESPONSE_TIME_MICROS} ( Microsecond ) %{RESPONSE_TIME_NANOS}( nanosecond ) nothing ResponseTimeAttribute

Be careful : Default undertow There is no open request time statistics , You need to open it to count the response time , How to turn it on ? By registering a WebServerFactoryCustomizer To Spring ApplicationContext Then you can . Look at the code below ( Project address :https://github.com/HashZhang/spring-cloud-scaffold/blob/master/spring-cloud-iiford/):

spring.factories( Omit irrelevant code )

# AutoConfiguration
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.github.hashjang.spring.cloud.iiford.service.common.auto.UndertowAutoConfiguration

UndertowAutoConfiguration

// Set up proxyBeanMethods=false, Because no @Bean You need to return the same Bean, There's no need to be an agent , Turn off to increase startup speed 
@Configuration(proxyBeanMethods = false)
@Import(WebServerConfiguration.class)
public class UndertowAutoConfiguration {
}

WebServerConfiguration

// Set up proxyBeanMethods=false, Because no @Bean You need to return the same Bean, There's no need to be an agent , Turn off to increase startup speed 
@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();
// If accesslog The response time is printed in the configuration , Then open the record request start time configuration
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;
}
// Judge accesslog Whether the view response time is configured
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);
}
}

other

And security related properties (SSL relevant , Login authentication Authentication relevant ), Microservice internal calls are generally not used , We won't go into details here .

Other built-in properties , stay Spring Boot It's not used in the environment , We won't discuss it here .

give an example

What we first configured accesslog The request returns as follows ( JSON The formatted result ):

{
"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",
}

Spring Cloud The way to upgrade - 2020.0.x - 3. Undertow Of accesslog More articles on configuration

  1. Spring Cloud Upgrade to the latest Finchley edition , Step on the hole guide !

    https://blog.csdn.net/youanyyou/article/details/81530240 Spring Cloud Upgrade to the latest Finchley edition , Stepped on all the pits ! 2018 year ...

  2. Spring Cloud Upgrade to the latest Greenwich edition , Comfortable. ~

    Last year will be Spring Cloud Upgrade to Finchley edition : Spring Cloud Upgrade to the latest Finchley edition , Stepped on all the pits ! The stack leader of this large version stepped on a lot of pits , Helped a lot of friends . ...

  3. spring cloud: Hystrix( Two ): Easy to use @HystrixCommand Of commandProperties To configure @HistrixProperty Isolation strategy

    spring cloud: Hystrix( Two ): Easy to use @HystrixCommand Of commandProperties To configure @HistrixProperty Isolation strategy An e-commerce website on a black Friday ...

  4. Spring Cloud Upgrade to the latest Finchley edition , Stepped on all the pits !

    Spring Boot 2.x It has been released for a long time , Now? Spring Cloud Also released be based on Spring Boot 2.x Of Finchley edition , Now let's do an overall framework upgrade for the project . Before upgrading ...

  5. spring cloud: Upgrade to spring boot 2.x/Finchley.RELEASE Pit encountered

    spring boot2.x It's been a while , and spring cloud The latest Release edition Finchley.RELEASE, The default integration is spring boot 2.x, I will try an old project these days ...

  6. 【Finchley】【 Upgrade changes 】Spring Cloud Upgrade to Finchley What should be noted after the release

    Spring Boot 2.x It has been released for a long time , Now? Spring Cloud Also released be based on Spring Boot 2.x Of Finchley edition , Now let's do an overall framework upgrade for the project . Before upgrading ...

  7. Spring Cloud Advanced road | Two : Service providers (discovery)

    1 Create parent project As mentioned above , With spring boot 2.1.7.RELEASE As the base ,spring cloud Version is Greenwich.SR2,spring cloud alibaba Version is 2.1.0 ...

  8. Java Spring Cloud The road of actual combat - 1 Create project

    0. Preface The project uses Maven Manage and build , So it needs to be pre configured Maven. Um. , I don't want to introduce too much in this series . 1. Create project So let's create one pom.xml file , Add the following : <?xml v ...

  9. 【Java Spring Cloud The road of actual combat 】- Use Nacos And the creation of gateway Center

    0. Preface In the last section , We created a project architecture , Subsequent projects will add to that architecture . 1. Nacos 1.1 brief introduction Nacos Can be used to discover . Configure and manage microservices . Provides an easy-to-use feature set , It can move quickly ...

  10. 【Java Spring Cloud The road of actual combat 】 Add one SpringBootAdmin monitor

    0. Preface In the previous chapters , We built a project skeleton first , And set up another one to use nacos Of gateway Gateway project , There are not too many things configured in the gateway project . Now we're going to build it in Spring Cloud Another focus of microservice ...

Random recommendation

  1. PHP Get the millisecond timestamp , utilize microtime() function

    PHP Get the millisecond timestamp , utilize microtime() function php There is no function to return milliseconds , But it provides a microtime() function , With this function , It's easy to define a function that returns milliseconds .php Millisecond is no default ...

  2. db2 stored procedure grammar And result set query

    Using stored procedures for the first time , About dealing with to-do , I don't know how to execute and transfer parameters Give stored procedures , In fact, it's very simple . @call PRC_MISSIONLIST_QUERY('27020214', '27040000', ' ...

  3. [Javascript] Drawing Paths - Curves and Arcs

    window.onload = function() { var canvas = document.getElementById("canvas"), context = can ...

  4. Linux Learn the eighteen 、 Make good use of judgment

    Original address :http://vbird.dic.ksu.edu.tw/linux_basic/0340bashshell-scripts_3.php Make good use of judgment In Chapter 11 , We mentioned  $?  What this variable does is ...

  5. Shell And command base

    What is? Shell Shell It's the user interface of the system , It provides an interface for users to interact with the kernel ( Command parser ),Shell Receive the user input command and send it to the kernel to execute , The structure is as follows: Shell The function of Shell The most important ...

  6. jdk Source reading notes -ArrayList

    One .ArrayList summary First let's talk about it ArrayList What is it? ? What problem does it solve ?ArrayList It's actually an array , But it's different from ordinary arrays , It's a dynamic array that can change size dynamically .ArrayList ...

  7. 【Zabbix】Zabbix-agent Automation script

    zabbix-agent Automation script effect : Mass deployment zabbix-agent. For hundreds of virtual machines can be Zabbix monitor . Script name :inst-agent.sh #!/bin/bash echo " ...

  8. Every line of code has a record — How to use git Step by step explore the history of the project

    Why is the page so simple?Every line of code has a hidden piece of document information . The following code snippet, no matter who wrote it , Its first 4 OK, for some reason, I want to visit a DOM Nodal clientLeft attribute , But it doesn't deal with the results . It's very puzzling , Can you tell me why they want to ...

  9. Json To CSharp

    This is a tools for generate json reader classes. In some case, when we get a json data, we hope to ...

  10. Daily Scrum NO.3

    Work Overview Fu Meixiao (PM) The work done yesterday 1.Daily Scrum. Daily meeting and daily work distribution and check . 2. Integrate the various DEV Code written , stay TFS on Beta Phase first code check in . Work today 1.Daily ...