blob: e58efe1f38bdafee83062425ef85a6c1d3a495a2 [file] [log] [blame]
/**
********************************************************************************
* Copyright (c) 2021 Robert Bosch GmbH and others.
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Robert Bosch GmbH - initial API and implementation
********************************************************************************
*/
package org.eclipse.app4mc.util.sessionlog;
import java.io.File;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.concurrent.CopyOnWriteArrayList;
import org.eclipse.app4mc.util.sessionlog.SessionLogEntry.Status;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.osgi.service.component.annotations.ReferencePolicyOption;
/**
* Service factory to create a service that can be used to collect session log
* statements, e.g. for a migration or a transformation session. The collected
* log statements can then be flushed via SessionLogWriter services, e.g. to a
* file or to the console.
*/
@Component(factory = "org.eclipse.app4mc.amalthea.sessionlog.factory", service = SessionLogger.class)
public class SessionLogger {
CopyOnWriteArrayList<SessionLogWriter> logWriter = new CopyOnWriteArrayList<>();
ArrayList<SessionLogEntry> log = new ArrayList<>();
public void error(String msg, Object... args) {
String message = (args != null && args.length > 0) ? MessageFormat.format(msg, args) : msg;
Exception e = null;
if (args != null && args.length > 0 && args[args.length - 1] instanceof Exception) {
e = (Exception) args[args.length - 1];
}
this.log.add(new SessionLogEntry(Status.ERROR, "ERROR: " + message, e));
}
public void warn(String msg, Object... args) {
String message = (args != null && args.length > 0) ? MessageFormat.format(msg, args) : msg;
this.log.add(new SessionLogEntry(Status.WARNING, "WARN : " + message));
}
public void info(String msg, Object... args) {
String message = (args != null && args.length > 0) ? MessageFormat.format(msg, args) : msg;
this.log.add(new SessionLogEntry(Status.INFO, "INFO : " + message));
}
public void flush(File sessionLogFile) {
this.logWriter.forEach(w -> w.write(sessionLogFile, new ArrayList<>(this.log)));
this.log.clear();
}
@Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC, policyOption = ReferencePolicyOption.GREEDY)
public void registerLogWriter(SessionLogWriter writer) {
this.logWriter.add(writer);
}
public void unregisterLogWriter(SessionLogWriter writer) {
this.logWriter.remove(writer);
}
}