How can I print different logs for different user roles in Java?

50 Views Asked by At

I'm trying to do logging for different user roles (admin, developers, end users, etc.), and I want to show a different/filtered log for end-users. How can I achieve that?

How can I approach this problem?

1

There are 1 best solutions below

0
Lino On

You could probably tackle this problem with using something like a ThreadLocal variable in your logging filter. That is set by the code that does the authentication. And based on that do your different logging.

A simple example, in your filter class you could have something like this:

private static final ThreadLocal<String> ROLE = new ThreadLocal<>();

public void doTheFiltering() {
    String role = ROLE.get();
    if (role == null) {
        // not authenticated...
    } else if (role.equals("ADMIN") {
        // filter based on admin privileges
    } else ...
}

public static void setRole(String role) {
    ROLE.set(role);
}

public static void clearRole() {
    ROLE.remove();
}

And in your authentication code:

try {
    String role = ... // find out role
    MyFilter.setRole(role);
    // continue with whatever you're doing
} finally {
    // clean up the role on this thread.
    // this is especially needed when you're using a thread pool that handles requests.
    MyFilter.clearRole();
}