0
votes

i am struggling with Spring Boot Loggin. I am not able to print log.info or log.error on my console. Here is my pom.xml file and application.properties also. I am wondering why is this behaviour happening as I do not have any specific declarations in my pom file.

<?xml version="1.0" encoding="UTF-8"?>

4.0.0 org.springframework.boot spring-boot-starter-parent 2.4.0-SNAPSHOT com.jgeekmz ManagementApp 0.0.1-SNAPSHOT ManagementApp Application for Management

<properties>
    <java.version>11</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
    </dependency>

    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity5</artifactId>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>

    <dependency>
        <groupId>jakarta.validation</groupId>
        <artifactId>jakarta.validation-api</artifactId>
        <version>2.0.2</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.nulab-inc/zxcvbn -->
    <dependency>
        <groupId>com.nulab-inc</groupId>
        <artifactId>zxcvbn</artifactId>
        <version>1.3.0</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
        <version>2.2.5.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-commons</artifactId>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

<repositories>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/milestone</url>
    </repository>
    <repository>
        <id>spring-snapshots</id>
        <name>Spring Snapshots</name>
        <url>https://repo.spring.io/snapshot</url>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
</repositories>
<pluginRepositories>
    <pluginRepository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/milestone</url>
    </pluginRepository>
    <pluginRepository>
        <id>spring-snapshots</id>
        <name>Spring Snapshots</name>
        <url>https://repo.spring.io/snapshot</url>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </pluginRepository>
</pluginRepositories>
package com.jgeekmz.ManagementApp;

 import com.jgeekmz.ManagementApp.models.Post;
 import com.jgeekmz.ManagementApp.models.User;
 import com.jgeekmz.ManagementApp.repositories.*;
 import com.jgeekmz.ManagementApp.services.PostService;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Controller;
 import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;

@Controller public class ApplicationController { Logger log = LoggerFactory.getLogger(ApplicationController.class);

private final VehicleRepository vehicleRepo;
private final EmployeeRepository employeeRepo;
private final LocationRepository locationRepo;
private final PostService postService;
private final PostRepository postRepo;
private final UserRepository userRepository;

@Autowired
public ApplicationController(VehicleRepository vehicleRepo, EmployeeRepository employeeRepo, 
LocationRepository locationRepo, PostService postService, PostRepository postRepo, UserRepository 
userRepository) {
    this.vehicleRepo = vehicleRepo;
    this.employeeRepo = employeeRepo;
    this.locationRepo = locationRepo;
    this.postService = postService;
    this.postRepo = postRepo;
    this.userRepository = userRepository;
}

//Index page plus count vehicles, users, employees, locations. Find all posts.
@RequestMapping(value = "/index", method = RequestMethod.GET)
public String goHome(Model model) {
    // System.out.println(model);
    // System.out.println(repo);
    // long t = repo.count();
    // System.out.println(t);
    // System.out.println(postRepo);
    model.addAttribute("tcount", vehicleRepo.count());
    model.addAttribute("empcount", employeeRepo.count());
    model.addAttribute("locations", locationRepo.count());
    model.addAttribute("posts", postRepo.findAll());
    model.addAttribute("tusers", userRepository.count());
    return "index";
}

@RequestMapping("/")
public String goDashboard() {
    return "/index";
}

//Add new post on the index page
@RequestMapping(value = "/index/addNewPost", method = RequestMethod.POST)
public String addNewPost(Post post) {
    System.out.println(post);
    postService.save(post);
    return "redirect:/index";
}

//@GetMapping("/users/checkUser")
@RequestMapping(value = "/users/checkUser", method = RequestMethod.GET)
public RedirectView checkUser(@ModelAttribute("user") User user, RedirectAttributes redir) {
    //User usr = new User();
    String usrName = user.getUsername();
    log.info("User" + usrName);
    User userName = userRepository.findByUsername(usrName);
    Boolean checkUserValidation;
    checkUserValidation = userRepository.findByEnabled(usrName);

   /* User valid = userRepository.findByEnabled(usrName);
    System.out.println(valid);*/

    RedirectView redirectView = new RedirectView("/login", true);
    RedirectView redirectViewTwo = new RedirectView("/index", true);
    redir.addFlashAttribute("messageUserNotExist", "User is not being registered!");
    // redir.addFlashAttribute("messageUserExist", "User already exist!");

    log.error(">>>> Logged user: " + userRepository.findByUsername(usrName));

    if (userName != null) {
        if (checkUserValidation) {
            log.error("User exist!");
            System.out.println("Logged in!");
            System.err.println("This is an error message");
            return redirectViewTwo;
        }
    }
    log.error("User does not exist!");
    return redirectView;
}

/*  //Going to home page
@GetMapping("/index")
public String goHome () { return "index"; }*/

@GetMapping("/login")
public String login() {
    return "login";
}

@GetMapping("/changePassword")
public String changePassword() {
    return "changePassword";
}

@GetMapping("/logout")
public String logout() {
    return "login";
}

 /*  @GetMapping("/register")
public String register(@ModelAttribute("user") User user) { return "register"; }*/

@GetMapping("/blank")
public String getBlank() {
    return "blank";
}

}

application.properties

3
Firts of all ! REMOVE THE PASSWORD from the application.properties - Zorglube
Try logging conf keys - Zorglube
Hello, Zorglube, I have tried with loggin.level and etc., also with hibernate properties, but nothing is helping. Also the system.out.println() is not working. I am not able to debug anything. Have removed the pass!!! THANKS! Any other suggestions? - mzhack
Did you tried using Slf4j, I'm usiing it with Spring boot it work perfectly fine. - Zorglube
Or try @Beppe-C solution. - Zorglube

3 Answers

0
votes

Enable logging in the application.properties

logging.level.root=WARN
logging.level.com.jgeekmz=DEBUG

logging.pattern.console=%clr(%5p) [%logger{0}] %m%n
0
votes

I think you should add logback.xml file if you want to specify what you want to do, you have to add it in the ressources folder:

Here is an example where you can log a specific package if you want ... :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<configuration scan="true" scanPeriod="5 minutes">
    <property name="LOG_ROOT" value="logs" />
    <property name="application-name" value="ms-pilotage" />
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout"> <Pattern>%d{dd/MM/yyyyHHss.SSS} [%thread] %-5level %logger{36} - %msg%n </Pattern> </layout>
    </appender>

    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <File>${LOG_ROOT}/${application-name}.log</File>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <FileNamePattern>${LOG_ROOT}/archives/${application-name}.%d{yyyy-MM-dd}.%i.zip</FileNamePattern>
            <maxFileSize>50MB</maxFileSize>
            <maxHistory>200</maxHistory>
        </rollingPolicy>
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>%-26(%d{HH🇲🇲ss.SSS} [%thread]) %-5level %logger{32} - %msg%n</Pattern>
        </layout>
        <Append>false</Append>
    </appender>

    <appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender">
        <appender-ref ref="FILE" />
        <discardingThreshold>0</discardingThreshold>
        <includeCallerData>true</includeCallerData>
        <queueSize>1000</queueSize>
    </appender>

    <logger name="org.hibernate.SQL" level="DEBUG" additivity="false">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="ASYNC" />
    </logger>
    <logger name="org.hibernate.type.descriptor.sql.BasicBinder" additivity="false">
        <level value="TRACE" />
        <appender-ref ref="STDOUT"></appender-ref>
        <appender-ref ref="ASYNC" />
    </logger>

    <root level="INFO">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="ASYNC" />
    </root>


</configuration>
0
votes

nope still not able to do logging on the console. I have added dev-tool dependency, but nevertheless not possible to print any kind of debug trace.

My check mapping:

@RequestMapping(value = "/checkUser", method = RequestMethod.POST)
    public RedirectView checkUser(User user, RedirectAttributes redir) {
    System.out.println("HERE!");

    //User usr = new User();
    String usrName = user.getUsername();
    User userName = userRepository.findByUsername(usrName);
    Boolean checkUserValidation;
    checkUserValidation = userRepository.findByEnabled(usrName);

    /* User valid = userRepository.findByEnabled(usrName);*/

    RedirectView redirectView = new RedirectView("/login", true);
    RedirectView redirectViewTwo = new RedirectView("/index", true);
    redir.addFlashAttribute("messageUserNotExist", "User is not being registered!");
    redir.addFlashAttribute("messageUserExist", "User already exist!");

    if (userName != null) {
        if (checkUserValidation) {
            System.out.println("User is logged in!!!!!!!!!!!" + 
            userRepository.findByUsername(usrName));
            System.out.println("HERE!");
            return redirectViewTwo;
        } else {
            System.out.println("FALSE");
        }
    }
    return redirectView;
}

And my Spring Security settings:

    @Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/registerPage2", "/login", "/confirm","/users/**", 
            "/resources/**", "/css/**", "/js/**" ,"/fonts/**", "/img/**").permitAll()
            .anyRequest()
            .authenticated()
            .and()
                .formLogin()
                .loginPage("/login").permitAll()
                .loginProcessingUrl("/checkUser")
                .defaultSuccessUrl("/index",true)

            .and()
                .logout()
                .invalidateHttpSession(true)
                .clearAuthentication(true)
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/login").permitAll();
}

Basically I want to let the admin person to activate the account first, then the user to receive an email with confirmation message that his account is now active and he can log in. My idea was to do this mapping make the check and than let him login. But I assume this mapping was not working as I am using Spring Security and everything is there handle.

Is it my way the proper one or I should implement UserDetailService and use it.

Also my login form section:

  <form class="login-form" th:action="@{/checkUser}" method="post" th:object="${user}">

<!-- Success Massage for the user after registration -->
<div style="text-align: center; font-size: 15px; color: #797979; font-weight: bold">
  <span style="color: yellow;" th:utext="${message}"></span>
  <span style="color: yellow;" th:utext="${messageUserNotExist}"></span>
</div>
<div class="login-wrap">
  <p class="login-img"><i class="icon_lock_alt"></i></p>
  <div class="input-group">
    <span class="input-group-addon"><i class="icon_profile"></i></span>
    <input type="text" class="form-control" placeholder="Username" id="username" name="username" autofocus>
  </div>
  <div class="input-group">
    <span class="input-group-addon"><i class="icon_key_alt"></i></span>
    <input type="password" class="form-control" placeholder="Password" id="password" name="password" autocomplete="off">
  </div>
  <!--<label class="checkbox">
       <span class="pull-right"><input type="submit" value="Login" onclick="lsRememberMe()"></span>
  </label>-->

  <span class="pull-right"><input type="checkbox" value="lsRememberMe" id="rememberMe"> Remember me </span>
  <span class="pull-left"><a th:href="@{/forgotPassword}">Forgot Password?</a></span>
  <span><button class="btn btn-primary btn-lg btn-block" type="submit" value="Login" id="submit" onclick="lsRememberMe()">Login</button></span>
  <a th:href="@{/registerPage2}" class="btn btn-info btn-lg btn-block">Sign Up</a>

  <!-- <a th:href="@{/users/checkUser}" class="btn btn-info btn-lg btn-block"> Login</a> -->
  <!-- <input type="submit" value="Login" onclick="lsRememberMe()"> -->
  <!-- <button class="btn btn-primary btn-lg btn-block" type="submit" value="Login" onclick="lsRememberMe()">Login</button> -->
</div>