Skip to content

Commit

Permalink
Configure logging (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
domi-b authored Nov 20, 2024
2 parents eb839b3 + 14d7aa1 commit 5d901d2
Show file tree
Hide file tree
Showing 6 changed files with 110 additions and 21 deletions.
4 changes: 4 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ dependencies {

implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-csv:2.18.1'

implementation platform('org.apache.logging.log4j:log4j-bom:2.24.1')
implementation 'org.apache.logging.log4j:log4j-api'
implementation 'org.apache.logging.log4j:log4j-core'

testImplementation platform('org.junit:junit-bom:5.10.0')
testImplementation 'org.junit.jupiter:junit-jupiter'
}
Expand Down
23 changes: 23 additions & 0 deletions src/main/java/ch/geowerkstatt/lk2dxf/EhiLogAdapter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package ch.geowerkstatt.lk2dxf;

import ch.ehi.basics.logging.LogEvent;
import ch.ehi.basics.logging.LogListener;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
* An adapter that forwards log events from an EhiLogger to a log4j Logger.
*/
public final class EhiLogAdapter implements LogListener {
private static final Logger LOGGER = LogManager.getLogger();

@Override
public void logEvent(LogEvent logEvent) {
switch (logEvent.getEventKind()) {
case LogEvent.ERROR -> LOGGER.error("{}", logEvent.getEventMsg());
case LogEvent.ADAPTION -> LOGGER.warn("{}", logEvent.getEventMsg());
case LogEvent.DEBUG_TRACE, LogEvent.STATE_TRACE -> LOGGER.trace("{}", logEvent.getEventMsg());
default -> LOGGER.info("{}", logEvent.getEventMsg());
}
}
}
71 changes: 60 additions & 11 deletions src/main/java/ch/geowerkstatt/lk2dxf/Main.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,23 @@
package ch.geowerkstatt.lk2dxf;

import ch.ehi.basics.logging.EhiLogger;
import ch.ehi.basics.logging.StdListener;
import ch.geowerkstatt.lk2dxf.mapping.ObjectMapper;
import ch.interlis.ili2c.metamodel.TransferDescription;
import ch.interlis.iox_j.utility.IoxUtility;
import com.vividsolutions.jts.geom.Geometry;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.appender.FileAppender;
import org.apache.logging.log4j.core.config.Configurator;
import org.apache.logging.log4j.core.layout.PatternLayout;

import java.io.File;
import java.util.List;
Expand All @@ -23,6 +33,8 @@ public final class Main {

private static final String VERSION;

private static final Logger LOGGER = LogManager.getLogger();

static {
String packageVersion = Main.class.getPackage().getImplementationVersion();
VERSION = packageVersion != null ? packageVersion : "unknown";
Expand All @@ -37,7 +49,9 @@ public static void main(String[] args) {
Options cliOptions = createCliOptions();
CommandLine commandLine = parseCommandLine(cliOptions, args);

if (commandLine.hasOption(OPTION_HELP)) {
if (commandLine == null) {
System.exit(1);
} else if (commandLine.hasOption(OPTION_HELP)) {
printUsage(cliOptions);
} else if (commandLine.hasOption(OPTION_VERSION)) {
System.out.println(VERSION);
Expand All @@ -47,12 +61,20 @@ public static void main(String[] args) {
printUsage(cliOptions);
System.exit(1);
} else {
processFiles(options.get());
configureLogging(options.get());
if (!processFiles(options.get())) {
System.exit(1);
}
}
}
}

private static void processFiles(LK2DxfOptions options) {
/**
* Processes the input files and writes the generated DXF to the output file.
*
* @return {@code true} if the operation was successful, {@code false} otherwise.
*/
private static boolean processFiles(LK2DxfOptions options) {
Optional<Geometry> perimeter = options.parsePerimeter();

ObjectMapper objectMapper;
Expand All @@ -73,26 +95,53 @@ private static void processFiles(LK2DxfOptions options) {

objects.forEach(o -> o.writeToDxf(dxfWriter));
} catch (Exception e) {
System.err.println("Failed to process file: " + xtfFile);
e.printStackTrace();
return;
LOGGER.error("Failed to process file: {}", xtfFile, e);
return false;
}
}
} catch (Exception e) {
System.err.println("Failed to write DXF file: " + options.dxfFile());
e.printStackTrace();
return;
LOGGER.error("Failed to write DXF file: {}", options.dxfFile(), e);
return false;
}

return true;
}

private static void configureLogging(LK2DxfOptions lk2DxfOptions) {
Level logLevel = lk2DxfOptions.trace() ? Level.TRACE : Level.INFO;
Configurator.setRootLevel(logLevel);

if (lk2DxfOptions.logfile().isPresent()) {
var layout = PatternLayout.newBuilder()
.withPattern("%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n")
.build();
var fileAppender = FileAppender.newBuilder()
.setName("Logfile")
.setLayout(layout)
.withFileName(lk2DxfOptions.logfile().get())
.withAppend(false)
.build();
var rootLogger = (org.apache.logging.log4j.core.Logger) LogManager.getRootLogger();
rootLogger.get().addAppender(fileAppender, logLevel, null);
fileAppender.start();
}

EhiLogger.getInstance().addListener(new EhiLogAdapter());
EhiLogger.getInstance().removeListener(StdListener.getInstance());

LOGGER.info("lk2dxf version {}", VERSION);
LOGGER.info("ili2c version {}", TransferDescription.getVersion());
LOGGER.info("iox-ili version {}", IoxUtility.getVersion());
LOGGER.info("Transfer files: {}", lk2DxfOptions.xtfFiles());
}

private static CommandLine parseCommandLine(Options options, String[] args) {
try {
DefaultParser parser = new DefaultParser();
return parser.parse(options, args);
} catch (ParseException e) {
System.err.println("Error parsing command line arguments: " + e.getMessage());
LOGGER.error("Error parsing command line arguments: {}", e.getMessage());
printUsage(options);
System.exit(1);
return null;
}
}
Expand Down
6 changes: 4 additions & 2 deletions src/main/java/ch/geowerkstatt/lk2dxf/MappedObject.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import ch.interlis.iox_j.jts.Iox2jtsext;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public record MappedObject(
String oid,
Expand All @@ -18,6 +20,7 @@ public record MappedObject(
String text,
LayerMapping layerMapping) {
private static final GeometryFactory GEOMETRY_FACTORY = new JtsextGeometryFactory();
private static final Logger LOGGER = LogManager.getLogger();

/**
* Creates a new {@link MappedObject} that contains all information to process the object further.
Expand Down Expand Up @@ -59,8 +62,7 @@ public void writeToDxf(DxfWriter dxfWriter) {
default -> throw new AssertionError("Unknown output type: " + layerMapping().output());
}
} catch (Exception e) {
System.err.println("Failed to write object: " + oid() + " to dxf.");
e.printStackTrace();
LOGGER.error("Failed to write object: {} to dxf.", oid(), e);
}
}
}
13 changes: 9 additions & 4 deletions src/main/java/ch/geowerkstatt/lk2dxf/XtfStreamReader.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
import ch.interlis.iox.StartTransferEvent;
import ch.interlis.iox_j.logging.LogEventFactory;
import ch.interlis.iox_j.utility.ReaderFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.File;
import java.util.Spliterator;
Expand All @@ -24,8 +26,10 @@
*/
public final class XtfStreamReader implements AutoCloseable {
private static final ReaderFactory READER_FACTORY = new ReaderFactory();
private static final Logger LOGGER = LogManager.getLogger();

private final IoxReader reader;
private final String filename;
private LKMapXtfReaderState state = null;

/**
Expand All @@ -37,6 +41,7 @@ public XtfStreamReader(File xtfFile) throws IoxException {
LogEventFactory logEventFactory = new LogEventFactory();
Settings settings = new Settings();
this.reader = READER_FACTORY.createReader(xtfFile, logEventFactory, settings);
this.filename = xtfFile.getName();
}

/**
Expand Down Expand Up @@ -82,14 +87,14 @@ public boolean tryAdvance(Consumer<? super IomObject> action) {
throw new IllegalStateException("Unexpected start transfer event in state: " + state);
}
state = LKMapXtfReaderState.TRANSFER;
System.out.println("Start transfer");
LOGGER.info("Start transfer of \"{}\"", filename);
}
case StartBasketEvent startBasketEvent -> {
if (state != LKMapXtfReaderState.TRANSFER) {
throw new IllegalStateException("Unexpected start basket event in state: " + state);
}
state = LKMapXtfReaderState.BASKET;
System.out.println("Start basket \"" + startBasketEvent.getBid() + "\"");
LOGGER.info("Start basket \"{}\"", startBasketEvent.getBid());
}
case ObjectEvent objectEvent -> {
if (state != LKMapXtfReaderState.BASKET) {
Expand All @@ -103,14 +108,14 @@ public boolean tryAdvance(Consumer<? super IomObject> action) {
throw new IllegalStateException("Unexpected end basket event in state: " + state);
}
state = LKMapXtfReaderState.TRANSFER;
System.out.println("End basket");
LOGGER.info("End basket");
}
case EndTransferEvent ignored -> {
if (state != LKMapXtfReaderState.TRANSFER) {
throw new IllegalStateException("Unexpected end transfer event in state: " + state);
}
state = LKMapXtfReaderState.COMPLETED;
System.out.println("End transfer");
LOGGER.info("End transfer of \"{}\"", filename);
return false;
}
default -> throw new IllegalStateException("Unexpected iox event: " + event);
Expand Down
14 changes: 10 additions & 4 deletions src/main/java/ch/geowerkstatt/lk2dxf/mapping/ObjectMapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
import ch.interlis.iom.IomObject;
import ch.interlis.iom_j.Iom_jObject;
import ch.interlis.iox_j.validator.Value;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.File;
import java.io.IOException;
Expand All @@ -33,6 +35,8 @@

public final class ObjectMapper {
private static final String MODELS_RESOURCE = "/models";
private static final Logger LOGGER = LogManager.getLogger();

private final List<LayerMapping> layerMappings;
private final TransferDescription transferDescription;

Expand Down Expand Up @@ -332,7 +336,7 @@ private static TransferDescription getTransferDescription(List<LayerMapping> lay
}

try {
System.out.println("iliModelsPath: " + iliModelsPath);
LOGGER.debug("iliModelsPath: {}", iliModelsPath);
var modelManager = new IliManager();
modelManager.setRepositories(new String[]{iliModelsPath});
var ili2cConfig = modelManager.getConfig(requiredModels, 0.0);
Expand Down Expand Up @@ -369,11 +373,11 @@ public Stream<MappedObject> mapObjects(Stream<IomObject> iomObjects) {
private Optional<MappedObject> mapObject(IomObject iomObject, Map<String, IomObject> objectCache, Set<IomObject> objectsWithUnresolvedRef, boolean unresolvedReferencesAllowed) {
var element = transferDescription.getElement(iomObject.getobjecttag());
if (element == null) {
System.out.println("No element found for object with id \"" + iomObject.getobjectoid() + "\".");
LOGGER.error("No element \"{}\" found for object with id \"{}\".", iomObject.getobjecttag(), iomObject.getobjectoid());
return Optional.empty();
}
if (!(element instanceof AbstractClassDef<?> classDef)) {
System.out.println("Element is not an AbstractClassDef for object with id \"" + iomObject.getobjectoid() + "\".");
LOGGER.error("Element \"{}\" is not an AbstractClassDef for object with id \"{}\".", iomObject.getobjecttag(), iomObject.getobjectoid());
return Optional.empty();
}

Expand Down Expand Up @@ -413,6 +417,8 @@ private Optional<MappedObject> mapObject(IomObject iomObject, Map<String, IomObj
default -> { } // MATCH, continue with next filter
}
}

LOGGER.trace("Mapped object of type \"{}\" with id \"{}\" to layer \"{}\".", iomObject.getobjecttag(), iomObject.getobjectoid(), mapper.mapping().layer());
return Optional.of(new MappedObject(
iomObject.getobjectoid(),
Optional.ofNullable(resolve(iomObject, mapper.geometry(), objectCache).getComplexObjects()).map(Collection::iterator).map(Iterator::next).orElse(null),
Expand All @@ -424,7 +430,7 @@ private Optional<MappedObject> mapObject(IomObject iomObject, Map<String, IomObj
}

// no match found
System.out.println("No match found for object with id \"" + iomObject.getobjectoid() + "\".");
LOGGER.warn("No match found for object of type \"{}\" with id \"{}\".", iomObject.getobjecttag(), iomObject.getobjectoid());
return Optional.empty();
}

Expand Down

0 comments on commit 5d901d2

Please sign in to comment.