简体   繁体   中英

Log4j2 Can I include users' name in pattern layout of log4j2?

Im using Log4j2 as logger in my app. I want to customize the logger message and include the logged in user's name as part of the pattern layout eg: 2021-06-01 03:29:06.636 [CURRENT_USER] WARN 1 --- [nio-8002-exec-7] com.zaxxer.hikari.pool.PoolBase: HikariPool-1 - Failed to validate connection org.postgresql.jdbc.PgConnection@6813ce6c (This connection has been closed.). Possibly consider using a shorter maxLifetime value.

I presume by logged in user you refer to the database user of the active transaction. If you can put that in an MDC variable (there are multiple ways to access to the JDBC user name, pick the one that suits your need best), then you can access to that value via the PatternLayout s %X directive, eg, %X{jdbcUserName} .

If you are referring to the database username, use Volkan Yazıcı's answer . If you want the operating system username, you can get that from the Java system property "user.name", and you can use the pattern ${sys:system.property.name} in your config (you'll need to double the $ character).

<pattern>... [$${sys:user.name}] ...</pattern>

Resolved. Used the bearer token to get user credentials then put the username by ThreadContext.

           if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            UserCredential user = JWTUtil.parseToken(bearerToken.substring(7, bearerToken.length()));
            ThreadContext.put("userName",  user.getUsername());

        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM