Search code examples
tinylog

How to set the path of the file writer to location of the jar using it?


So i recently switch from starting the jar file from a service rather than a script that first goes to the relevant directory. Is there a way to make sure that the path to the jar file is used instead of wherever the service started it? Inside the application i use the code below to get the correct path.

   try {
        Path p = Path.of(getClass().getProtectionDomain().getCodeSource().getLocation().toURI());

        workPath = p.getParent().toString();

        if( workPath.matches(".*[lib]")) { // Meaning used as a lib
            workPath = Path.of(workPath).getParent().toString();
        }
        settingsFile = Path.of(workPath, "settings.xml");
    } catch (URISyntaxException e) {
        Logger.error(e);
    }

Solution

  • Store your work path as system property:

    try {
        Path p = Path.of(getClass().getProtectionDomain().getCodeSource().getLocation().toURI());
    
        workPath = p.getParent().toString();
        if(workPath.matches(".*[lib]")) { // Meaning used as a lib
            workPath = Path.of(workPath).getParent().toString();
        }
    
        System.setProperty("tinylog.directory", workPath); // Set work path as system property
        settingsFile = Path.of(workPath, "settings.xml");
    } catch (URISyntaxException e) {
        Logger.error(e);
    }
    

    Use the system property in tinylog.properties:

    writer        = file
    writer.file   = #{tinylog.directory}/log.txt
    writer.format = {date: HH:mm:ss.SSS} {level}: {message}