Example usage for java.util.logging Logger log

List of usage examples for java.util.logging Logger log

Introduction

In this page you can find the example usage for java.util.logging Logger log.

Prototype

public void log(Level level, Supplier<String> msgSupplier) 

Source Link

Document

Log a message, which is only to be constructed if the logging level is such that the message will actually be logged.

Usage

From source file:nl.strohalm.cyclos.utils.logging.LoggingHandler.java

/**
 * Creates a new logger/*from www. jav  a 2  s  .com*/
 */
private Logger init(final Level level, final String file) {
    final LogSettings logSettings = settingsService.getLogSettings();
    final Logger logger = Logger.getAnonymousLogger();
    logger.setLevel(level);
    logger.setUseParentHandlers(false);
    try {
        final FileUnits units = logSettings.getMaxLengthPerFileUnits();
        final FileHandler fileHandler = new FileHandler(file,
                units.calculate(logSettings.getMaxLengthPerFile()), logSettings.getMaxFilesPerLog(), true);
        fileHandler.setFormatter(logFormatter);
        fileHandler.setEncoding(settingsService.getLocalSettings().getCharset());
        logger.addHandler(fileHandler);
    } catch (final Exception e) {
        final ConsoleHandler consoleHandler = new ConsoleHandler();
        consoleHandler.setFormatter(logFormatter);
        try {
            consoleHandler.setEncoding(settingsService.getLocalSettings().getCharset());
        } catch (final Exception e1) {
            // Just ignore
        }
        logger.addHandler(consoleHandler);
        logger.log(Level.WARNING, "Unable to create logger for file " + file);
    }
    return logger;
}

From source file:nl.strohalm.cyclos.utils.logging.LoggingHandler.java

/**
 * Log an account fee transfer// w ww  .  j  a  va 2s.c o m
 */
public void logAccountFeePayment(final Transfer transfer) {
    final Logger logger = getAccountFeeLogger();
    final Level level = AccountFeeLevel.DETAILED.getLevel();
    if (logger.isLoggable(level)) {
        final AccountFeeLog feeLog = transfer.getAccountFeeLog();
        final AccountFee fee = feeLog.getAccountFee();
        final UnitsConverter unitsConverter = settingsService.getLocalSettings()
                .getUnitsConverter(transfer.getFrom().getType().getCurrency().getPattern());
        String message;
        Object[] params;
        if (fee.getPaymentDirection() == PaymentDirection.TO_SYSTEM) {
            message = "Charged %s from %s";
            params = new Object[] { unitsConverter.toString(transfer.getAmount()),
                    transfer.getFrom().getOwnerName() };
        } else {
            message = "Paid %s to %s";
            params = new Object[] { unitsConverter.toString(transfer.getAmount()),
                    transfer.getTo().getOwnerName() };
        }
        try {
            logger.log(level, String.format(message, params));
        } catch (final Exception e) {
            System.out
                    .println("Error generating log on " + settingsService.getLogSettings().getAccountFeeFile());
        }
    }
}

From source file:eu.carrade.amaury.MinecraftChatModerator.managers.core.ConfigurationBasedManager.java

/**
 * Loads the classes registered by {@link #loadAfterFollowingConfig(Class)}, if enabled in the
 * configuration file.//from w  w w.  j av a  2s . co m
 *
 * <p>
 *     The configuration file format is the following.
 * </p>
 * <p>
 *     Each root-key of this configuration section must be the name of a managed class
 *     pre-registered using {@link #loadAfterFollowingConfig(Class)}, or this name without the
 *     trailing {@code suffix} (if it exists).<br />
 *     As example, with Bar? as the suffix, for the class FooBar?, the following keys will be
 *     accepted:
 *     <ul>
 *          <li>{@code FooBar} ; </li>
 *          <li>{@code Foo}.</li>
 *     </ul>
 * </p>
 * <p>
 *     The configuration sub-section? of each of these root keys can be of two different types.
 *     <ul>
 *         <li>
 *             <strong>No configuration section: a simple boolean.</strong><br />
 *             In this case, this boolean will represent the enabled? state of this filter.<br />
 *             No config will be transmitted to the subsequent managed object.<br />
 *             Example:
 *             <blockquote>
 *                 <pre>
 * FooBar: true
 *                 </pre>
 *             </blockquote>
 *         </li>
 *         <li>
 *             <strong>With a configuration section.</strong><br />
 *             The configuration section have to follow this format:
 *             <blockquote>
 *                 <pre>
 * FooBar:
 *     enabled: true  # or false
 *     options:
 *         # anything.
 *                 </pre>
 *             </blockquote>
 *             The {@code enabled} tag controls weither or not this is enabled.<br />
 *             The {@code options} configuration section represents the options passed to the
 *             constructor of the subsequent managed object (if such a constructor is present).
 *         </li>
 *     </ul>
 * </p>
 *
 * @param config The configuration section containing the whole config for this kind of managed
 *               things.
 * @param suffix The classes usual suffix removable from the class name to find the configuration
 *               key (see above).
 */
protected void load(ConfigurationSection config, String suffix) {
    final Logger logger = MinecraftChatModerator.get().getLogger();

    logger.info("Loading " + config.getName() + "...");

    for (Class<? extends MANAGED> type : toBeLoadedFromConfig) {
        final String managedName = type.getSimpleName();
        String configurationKey = managedName;

        if (!config.contains(configurationKey) && configurationKey.endsWith(suffix)) {
            configurationKey = configurationKey.substring(0, configurationKey.length() - suffix.length());
            if (!config.contains(configurationKey)) {
                logger.info(managedName + " not found in config - skipping.");
                continue;
            }
        }

        final Boolean enabled;
        final ConfigurationSection options;

        if (!config.isConfigurationSection(configurationKey)) // Simple case: managedName: true/false?.
        {
            enabled = config.getBoolean(configurationKey, false);
            options = null;
        } else // Complex case: configuration section with "enabled" and "options".
        {
            ConfigurationSection managedConfig = config.getConfigurationSection(configurationKey);

            enabled = managedConfig.getBoolean("enabled", false);
            options = managedConfig.isConfigurationSection("options")
                    ? managedConfig.getConfigurationSection("options")
                    : null;
        }

        if (!enabled)
            continue;

        MANAGED managedInstance;

        try {
            try {
                Constructor<? extends MANAGED> optionsConstructor = type
                        .getConstructor(ConfigurationSection.class);
                managedInstance = optionsConstructor.newInstance(options);
            } catch (NoSuchMethodException ignored) {
                try {
                    Constructor<? extends MANAGED> emptyConstructor = type.getConstructor();
                    managedInstance = emptyConstructor.newInstance();
                } catch (NoSuchMethodException e) {
                    logger.log(Level.SEVERE,
                            "Invalid constructor (neither with ConfigurationSection nor with nothing) in the "
                                    + managedName + " class (" + type.getName() + "), skipping.");
                    continue;
                }
            }
        } catch (InstantiationException | IllegalAccessException e) {
            logger.log(Level.SEVERE,
                    "Unable to load the " + managedName + " class (" + type.getName() + "), skipping.", e);
            continue;
        } catch (InvocationTargetException e) {
            logger.log(Level.SEVERE, "An exception occurred while loading " + managedName + ", skipping.",
                    e.getCause());
            continue;
        }

        register(managedInstance);
    }

    logger.info("Done.");
}

From source file:nl.strohalm.cyclos.utils.logging.LoggingHandler.java

/**
 * Log a successful transfer/*from w ww.  j a v  a  2  s.  c  om*/
 */
public void logTransfer(Transfer transfer) {
    final Logger logger = getTransactionLogger();
    final Level detailed = TransactionLevel.DETAILED.getLevel();
    final Level normal = TransactionLevel.NORMAL.getLevel();
    final boolean detailedLoggable = logger.isLoggable(detailed);
    final boolean normalLoggable = logger.isLoggable(normal);
    final boolean willLog = detailedLoggable || normalLoggable;
    // Generate log if, at least, normal level is enabled
    if (willLog) {
        transfer = fetchService.fetch(transfer, RelationshipHelper.nested(Transfer.Relationships.FROM,
                Account.Relationships.TYPE, AccountType.Relationships.CURRENCY), Transfer.Relationships.TO);
        Level level;
        final LocalSettings localSettings = settingsService.getLocalSettings();
        final UnitsConverter unitsConverter = localSettings
                .getUnitsConverter(transfer.getFrom().getType().getCurrency().getPattern());
        String message;
        Object[] args;
        // Get the specific level arguments
        if (detailedLoggable) {
            final TransferType type = transfer.getType();
            level = detailed;
            message = "id: %s, date: %s, type: %s (%s), amount: %s, from: %s, to: %s, by: %s, tx#: %s, description: %s";
            final Element by = transfer.getBy();
            args = new Object[] { transfer.getId(),
                    localSettings.getDateTimeConverter().toString(transfer.getDate()), type.getId(),
                    type.getName(), unitsConverter.toString(transfer.getAmount()),
                    transfer.getFrom().getOwnerName(), transfer.getTo().getOwnerName(),
                    by == null ? "<null>" : by.getUsername(),
                    StringUtils.defaultIfEmpty(transfer.getTransactionNumber(), "<null>"),
                    StringUtils.replace(transfer.getDescription(), "\n", "\\n") };
        } else {
            level = normal;
            message = "id: %s, amount: %s, from: %s, to: %s";
            args = new Object[] { transfer.getId(), unitsConverter.toString(transfer.getAmount()),
                    transfer.getFrom().getOwnerName(), transfer.getTo().getOwnerName() };
        }
        try {
            logger.log(level, String.format(message, args));
        } catch (final Exception e) {
            System.out.println(
                    "Error generating log on " + settingsService.getLogSettings().getTransactionFile());
        }
    }
}

From source file:nl.strohalm.cyclos.utils.logging.LoggingHandlerImpl.java

/**
 * Log a successful transfer/*from  w  ww . j  a  v  a2s  .  c  o m*/
 */
@Override
public void logTransfer(final Transfer transfer) {
    final Logger logger = getTransactionLogger();
    final Level detailed = TransactionLevel.DETAILED.getLevel();
    final Level normal = TransactionLevel.NORMAL.getLevel();
    final boolean detailedLoggable = logger.isLoggable(detailed);
    final boolean normalLoggable = logger.isLoggable(normal);
    final boolean willLog = detailedLoggable || normalLoggable;
    // Generate log if, at least, normal level is enabled
    if (willLog) {
        // transfer = fetchService.fetch(transfer, RelationshipHelper.nested(Payment.Relationships.FROM, Account.Relationships.TYPE,
        // AccountType.Relationships.CURRENCY), Payment.Relationships.TO);
        Level level;
        final LocalSettings localSettings = settingsService.getLocalSettings();
        final UnitsConverter unitsConverter = localSettings
                .getUnitsConverter(transfer.getFrom().getType().getCurrency().getPattern());
        String message;
        Object[] args;
        // Get the specific level arguments
        String loggedUser = LoggedUser.hasUser() ? LoggedUser.user().getUsername() : "<no logged user>";
        if (detailedLoggable) {
            final TransferType type = transfer.getType();
            level = detailed;
            message = "logged user: %s, id: %s, date: %s, type: %s (%s), amount: %s, from: %s, to: %s, by: %s, tx#: %s, description: %s";
            final Element by = transfer.getBy();
            args = new Object[] { loggedUser, transfer.getId(),
                    localSettings.getDateTimeConverter().toString(transfer.getDate()), type.getId(),
                    type.getName(), unitsConverter.toString(transfer.getAmount()),
                    transfer.getFrom().getOwnerName(), transfer.getTo().getOwnerName(),
                    by == null ? "<null>" : by.getUsername(),
                    StringUtils.defaultIfEmpty(transfer.getTransactionNumber(), "<null>"),
                    StringUtils.replace(transfer.getDescription(), "\n", "\\n") };
        } else {
            level = normal;
            message = "logged user: %s, id: %s, amount: %s, from: %s, to: %s";
            args = new Object[] { loggedUser, transfer.getId(), unitsConverter.toString(transfer.getAmount()),
                    transfer.getFrom().getOwnerName(), transfer.getTo().getOwnerName() };
        }
        try {
            logger.log(level, String.format(message, args));
        } catch (final Exception e) {
            System.out.println(
                    "Error generating log on " + settingsService.getLogSettings().getTransactionFile());
        }
    }
}

From source file:net.maxgigapop.mrs.driver.openstack.OpenStackModelBuilder.java

public static OntModel createOntology(String hostName, String tenantName, String tenantPasswd)
        throws IOException {

    String host = "charon.dragon.maxgigapop.net";
    String tenant = "admin";
    String tenantId;/*from  w w  w.  ja v  a 2  s .co m*/
    String token;

    Logger logger = Logger.getLogger(OpenStackModelBuilder.class.getName());

    OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_MICRO_RULE_INF);

    model.setNsPrefix("rdfs", "http://www.w3.org/2000/01/rdf-schema#");
    model.setNsPrefix("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
    model.setNsPrefix("xsd", "http://www.w3.org/2001/XMLSchema#");
    model.setNsPrefix("owl", "http://www.w3.org/2002/07/owl#");
    model.setNsPrefix("nml", "http://schemas.ogf.org/nml/2013/03/base#");
    model.setNsPrefix("mrs", "http://schemas.ogf.org/mrs/2013/12/topology#");

    Property hasNode = model.createProperty("http://schemas.ogf.org/nml/2013/03/base#hasNode");
    Property hasService = model.createProperty("http://schemas.ogf.org/nml/2013/03/base#hasService");
    Property providesVM = model.createProperty("http://schemas.ogf.org/mrs/2013/12/topology#providesVM");
    Property type = model.createProperty("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
    Property memory_mb = model.createProperty("http://schemas.ogf.org/mrs/2013/12/topology#memory_mb");
    Property num_core = model.createProperty("http://schemas.ogf.org/mrs/2013/12/topology#num_core");
    Property disk_gb = model.createProperty("http://schemas.ogf.org/mrs/2013/12/topology#disk_gb");

    Resource HypervisorService = model
            .createResource("http://schemas.ogf.org/mrs/2013/12/topology#HypervisorService");
    Resource Node = model.createResource("http://schemas.ogf.org/nml/2013/03/base#Node");
    Resource Topology = model.createResource("http://schemas.ogf.org/mrs/2013/12/topology#Topology");
    Resource VirtualSwitchService = model
            .createResource("http://schemas.ogf.org/mrs/2013/12/topology#VirtualSwitchService");
    Resource NamedIndividual = model.createResource("http://www.w3.org/2002/07/owl#NamedIndividual");
    Resource Nova = model.createResource("urn:ogf:network:dragon.maxgigapop.net:openstack-nova");
    Resource Neutron = model.createResource("urn:ogf:network:dragon.maxgigapop.net:openstack-neutron");
    Resource OpenstackTopology = model.createResource("urn:ogf:network:dragon.maxgigapop.net:topology");

    model.add(model.createStatement(OpenstackTopology, type, Topology));
    model.add(model.createStatement(OpenstackTopology, type, NamedIndividual));

    model.add(model.createStatement(Nova, type, HypervisorService));
    model.add(model.createStatement(Nova, type, NamedIndividual));

    model.add(model.createStatement(Neutron, type, VirtualSwitchService));
    model.add(model.createStatement(Neutron, type, NamedIndividual));

    token = OpenStackRESTClient.getToken(host, tenant, "admin", "admin");
    tenantId = OpenStackRESTClient.getTenantId(host, tenant, token);
    JSONArray novaDescription = OpenStackRESTClient.pullNovaConfig(host, tenantId, token);

    for (Object o : novaDescription) {

        JSONArray node = (JSONArray) ((JSONObject) o).get("host");

        if (node != null) {

            JSONObject resource = (JSONObject) ((JSONObject) node.get(0)).get("resource");
            String nodeName = (String) resource.get("host");
            Long numCpu = (Long) resource.get("cpu");
            Long memMb = (Long) resource.get("memory_mb");
            Long diskGb = (Long) resource.get("disk_gb");

            Resource computeNode = model.createResource("urn:ogf:network:dragon.maxgigapop.net:" + nodeName);
            Literal cpu = model.createTypedLiteral(numCpu);
            Literal mem = model.createTypedLiteral(memMb);
            Literal disk = model.createTypedLiteral(diskGb);

            model.add(model.createStatement(OpenstackTopology, hasNode, computeNode));
            model.add(model.createStatement(computeNode, type, Node));
            model.add(model.createStatement(computeNode, type, NamedIndividual));
            model.add(model.createStatement(computeNode, hasService, Nova));

            model.add(model.createStatement(computeNode, memory_mb, mem));
            model.add(model.createStatement(computeNode, disk_gb, disk));
            model.add(model.createStatement(computeNode, num_core, cpu));
        }

        JSONObject networkHost = (JSONObject) ((JSONObject) o).get("network_host");
        if (networkHost != null) {

            Resource networkNode = model.createResource(
                    "urn:ogf:network:dragon.maxgigapop.net:" + (String) networkHost.get("host_name"));

            model.add(model.createStatement(OpenstackTopology, hasNode, networkNode));
            model.add(model.createStatement(networkNode, type, Node));
            model.add(model.createStatement(networkNode, type, NamedIndividual));
            model.add(model.createStatement(networkNode, hasService, Neutron));
        }
    }

    tenantId = OpenStackRESTClient.getTenantId(host, "demo", token);
    token = OpenStackRESTClient.getToken(host, "demo", "demo", "demo");
    JSONArray vms = OpenStackRESTClient.pullNovaVM(host, tenantId, token);

    for (Object o : vms) {

        String vmName = (String) ((JSONObject) o).get("name");
        Resource vm = model.createResource("urn:ogf:network:dragon.maxgigapop.net:" + vmName);

        model.add(model.createStatement(vm, type, Node));
        model.add(model.createStatement(vm, type, NamedIndividual));

        model.add(model.createStatement(Nova, providesVM, vm));

    }

    /* 
    JSONArray ports = (JSONArray) OpenStackRESTClient.pullNeutron(host, tenantId, token).get("ports");        
    for(Object o : ports) {
            
            
    } */

    logger.log(Level.INFO, "Ontology model for OpenStack driver rewritten");

    return model;
}