// pom.xml
// If you are using spring-boot-starter-web, logging is automatically included with "spring-boot-starter-logging" jar

// application.properties
logging.level.org.springframework=debug // everything else will print as debug level
logging.level.[com.package.name]=trace // only this package will print as trace level

// Controlller
@Controller
public class SayHelloController {
    private Logger logger = LoggerFactory.getLogger(getClass());
	@RequestMapping("say-hello-jsp")
	// @RequestParam lets the url take a value as argument to a parameter payload
	// "ModelMap"  helps to pass data from controller to the specified view
	public String sayHelloJsp(@RequestParam(value="name", required = false)String name, ModelMap model){ 
		model.put("name",name); // the name variable now can be accessed in the view with "name" keyword
        // what you want to log
        System.out.println(name); // This is NOT RECOMMENDED in prod environment
        logger.debug(name); // debug level logging
        logger.info("This will print on info level"); // info level logging
        logger.warn("This will print on warn level"); // warn level logging
        logger.trace("This will print on trace level"); // warn level logging
		return "sayHello"; // the jsp file name
	}
}logging.level.org.springframework.jdbc.core.JdbcTemplate=DEBUG
logging.level.org.springframework.jdbc.core.StatementCreatorUtils=TRACElogging.level.org.springframework.web=INFO
logging.level.org.hibernate=ERROR
logging.level.net.guides=DEBUGlogging:
  level:
    org:
      springframework:
        security: DEBUG//  pom.xml
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.5</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.30</version>
</dependency>
// log4j.properties
log4j.rootLogger=INFO, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1} - %m%n
// application.properties
logging.level.org.springframework=debug
// ApplicationConfig.java
@Configuration
@PropertySource("classpath:application.properties")
@ComponentScan(basePackages = "com.frankmoley.lil.fid")
@EnableAspectJAutoProxy // Enable AOP
public class ApplicationConfig {
}
// Loggable annotation
@Target(ElementType.METHOD) // annotation should work on methods
@Retention(RetentionPolicy.RUNTIME) // annotation should be loaded during runtime
public @interface Loggable {
}
// Service
@Service
public class GreetingService {
    @Value("${app.greeting}")
    private String greeting;
    public GreetingService(){         super();     }
    @Loggable // This is the joinpoint : Where the aspected behavior is stitched
    public String getGreeting(String name){
        return greeting + " " + name; }
}
// Aspect class

@Component
@Aspect // ensure for component scanning
public class LoggingAspect {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoggingAspect.class);
    @Pointcut("@annotation(Loggable)") // connect with the annotation. The annotation is the pointcut (will trigger this aspect)
    public void executeLogging(){} // The original Advise : the logic that will run when annotation is called

    @Before(value = "executeLogging()")  // Pre-Advise: the logic that will run before execution of original advise
    public void logMethodCall(JoinPoint joinPoint){
        StringBuilder message = new StringBuilder("Method: "); // *root-start
        message.append(joinPoint.getSignature().getName());
        Object[] args = joinPoint.getArgs();
        if (null!=args && args.length>0){
            Arrays.asList(args).forEach(arg->{
                message.append(arg).append(" | ");
            }); // *root-end
        }
        LOGGER.info(message.toString());
    }
    
    @AfterReturning(value = "executeLogging()", returning = "returnValue") // Post-Advise: the logic that will run after execution of original advise
    public void logMethodCall(JoinPoint joinPoint, Object returnValue){
       // same as *root-start to *root-end
      // .. just work with returnValue
        if(returnValue instanceof Collection){ // *return-start
            message.append(", returning: ").append(((Collection)returnValue).size()).append(" instance(s)");
        }else{
            message.append(", returning: ").append(returnValue.toString());
        }
        LOGGER.info(message.toString()); // *return-end
    }
    
    @Around(value = "executeLogging()") // Most Flexible : Anything before original advise, anything after original advise returning value, anything after original advise returning exception
    public Object logMethodCall(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object returnValue = joinPoint.proceed();
        long totalTime = System.currentTimeMillis()-startTime;
        // same as *root-start to *root-end
        // same as *return-start to *return-end
        return returnValue;
    }
}spring.jpa.properties.hibernate.format_sql=trueimport org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MyApp {
    private static final Logger logger = LoggerFactory.getLogger(MyApp.class);
    
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
        
        // Logging example
        logger.trace("This is a TRACE level message.");
        logger.debug("This is a DEBUG level message.");
        logger.info("This is an INFO level message.");
        logger.warn("This is a WARN level message.");
        logger.error("This is an ERROR level message.");
    }
}logging.level.org.springframework.security=DEBUG/*
Create this class somwhere in your app directory structure
(More details on: https://www.baeldung.com/spring-http-logging - Section 5.1)
*/
@Configuration
public class RequestLoggingFilterConfig {

    @Bean
    public CommonsRequestLoggingFilter logFilter() {
        CommonsRequestLoggingFilter filter
                = new CommonsRequestLoggingFilter();
        filter.setIncludeQueryString(true);
        filter.setIncludePayload(true);
        filter.setMaxPayloadLength(10000);
        filter.setIncludeHeaders(false);
        filter.setAfterMessagePrefix("REQUEST DATA: ");
        return filter;
    }
}

/*
Add those to your application.properties file
(More details on: https://www.tutorialworks.com/spring-boot-log-to-file/)
*/
logging.level.org.springframework.web.filter.CommonsRequestLoggingFilter=DEBUG
logging.file.path=/home/logs
logging.file.name=myapp.log
Lombok has annotations for that.
Annotate your class with @Slf4j and a static log fiedl will be generated.

Java相关代码片段

array class methods in java

how to read all line from file java

Java int length

intent example in android

how to doubling size of an arrays in java

how to find my jdk path

how to handle multiple throws exception in java

spring boot jdbc for postgrest

factorial of a number

types of typecasting in java

types of assignment statement in java

Thread mutex

env files in spring boot

java over loading

logging in spring boot

how to split a list in multiple lists java

can two servlet have same urlpattern

spring debug

jsp spring

hanoi tower recursion java

java equals

age difference java

sed cheat sheet

java compare method

how to make a activity default in manifest

java max memory size

yum uninstall java

timestamp to long java

how to set background image in android studio

simple calculator in android

When to use HashMap vs Map

spring boot jpa

spring data jpa

spring jdbc

jpa vs hibernate

java with checking the password matching

profile in spring boot

string templates java

spring rest controller

java arraylist get item

com.oracle.jdbc

check if map is not empty java

how to install java 8 on debian 12

regex caractères spéciaux java

java 11 yum install

manage session in redis spring boot

java: error: release version 19 not supported

bean scope in spring

xml configuration in spring

spring cdi annotations

postconstruct and predestroy in spring

java decode_message

spring lazy initialization

java decorator design pattern

dependency injection in spring

check back pressed in fragment andorid

send email to any domain using java

record java

vs code setup for input/output in java

substring java

receive second word in string java

loose coupling in java

default value of char in java

spring boot repository pattern

spring boot h2 database

add security to spring admin

java islessthan method

Java implementation of recursive Binary Search

java round double

java downcasting

range of fibonacci series in java using recursion

java by anyone

solid java

equals() and hashcode() methods in java

android java map to bundle

android start activity with data

medium java 17

java import util list

bean life cycle in spring

spring boot aop