Search in sources :

Example 66 with SimpleFormatter

use of java.util.logging.SimpleFormatter in project tomcat70 by apache.

the class FileHandler method configure.

/**
 * Configure from <code>LogManager</code> properties.
 */
private void configure() {
    Timestamp ts = new Timestamp(System.currentTimeMillis());
    String tsString = ts.toString().substring(0, 19);
    date = tsString.substring(0, 10);
    // allow classes to override
    String className = this.getClass().getName();
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    // Retrieve configuration of logging file name
    rotatable = Boolean.parseBoolean(getProperty(className + ".rotatable", "true"));
    if (directory == null) {
        directory = getProperty(className + ".directory", "logs");
    }
    if (prefix == null) {
        prefix = getProperty(className + ".prefix", "juli.");
    }
    if (suffix == null) {
        suffix = getProperty(className + ".suffix", ".log");
    }
    // https://bz.apache.org/bugzilla/show_bug.cgi?id=61232
    boolean shouldCheckForRedundantSeparator = !rotatable && !prefix.isEmpty() && !suffix.isEmpty();
    // more, the notion of separator might be introduced
    if (shouldCheckForRedundantSeparator && (prefix.charAt(prefix.length() - 1) == suffix.charAt(0))) {
        suffix = suffix.substring(1);
    }
    pattern = Pattern.compile("^(" + Pattern.quote(prefix) + ")\\d{4}-\\d{1,2}-\\d{1,2}(" + Pattern.quote(suffix) + ")$");
    String sMaxDays = getProperty(className + ".maxDays", String.valueOf(DEFAULT_MAX_DAYS));
    if (maxDays <= 0) {
        try {
            maxDays = Integer.parseInt(sMaxDays);
        } catch (NumberFormatException ignore) {
        // no-op
        }
    }
    String sBufferSize = getProperty(className + ".bufferSize", String.valueOf(bufferSize));
    try {
        bufferSize = Integer.parseInt(sBufferSize);
    } catch (NumberFormatException ignore) {
    // no op
    }
    // Get encoding for the logging file
    String encoding = getProperty(className + ".encoding", null);
    if (encoding != null && encoding.length() > 0) {
        try {
            setEncoding(encoding);
        } catch (UnsupportedEncodingException ex) {
        // Ignore
        }
    }
    // Get logging level for the handler
    setLevel(Level.parse(getProperty(className + ".level", "" + Level.ALL)));
    // Get filter configuration
    String filterName = getProperty(className + ".filter", null);
    if (filterName != null) {
        try {
            setFilter((Filter) cl.loadClass(filterName).newInstance());
        } catch (Exception e) {
        // Ignore
        }
    }
    // Set formatter
    String formatterName = getProperty(className + ".formatter", null);
    if (formatterName != null) {
        try {
            setFormatter((Formatter) cl.loadClass(formatterName).newInstance());
        } catch (Exception e) {
            // Ignore and fallback to defaults
            setFormatter(new SimpleFormatter());
        }
    } else {
        setFormatter(new SimpleFormatter());
    }
    // Set error manager
    setErrorManager(new ErrorManager());
}
Also used : ErrorManager(java.util.logging.ErrorManager) SimpleFormatter(java.util.logging.SimpleFormatter) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Timestamp(java.sql.Timestamp) ParseException(java.text.ParseException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 67 with SimpleFormatter

use of java.util.logging.SimpleFormatter in project dataverse by IQSS.

the class AuthFilter method init.

@Override
public void init(FilterConfig filterConfig) throws ServletException {
    logger.info(AuthFilter.class.getName() + "initialized. filterConfig.getServletContext().getServerInfo(): " + filterConfig.getServletContext().getServerInfo());
    try {
        String glassfishLogsDirectory = "logs";
        FileHandler logFile = new FileHandler(".." + File.separator + glassfishLogsDirectory + File.separator + "authfilter.log");
        SimpleFormatter formatterTxt = new SimpleFormatter();
        logFile.setFormatter(formatterTxt);
        logger.addHandler(logFile);
    } catch (IOException ex) {
        Logger.getLogger(AuthFilter.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        Logger.getLogger(AuthFilter.class.getName()).log(Level.SEVERE, null, ex);
    }
}
Also used : SimpleFormatter(java.util.logging.SimpleFormatter) IOException(java.io.IOException) FileHandler(java.util.logging.FileHandler)

Example 68 with SimpleFormatter

use of java.util.logging.SimpleFormatter in project AndrOBD by fr3ts0n.

the class MainActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    // instantiate superclass
    super.onCreate(savedInstanceState);
    // requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    requestWindowFeature(Window.FEATURE_PROGRESS);
    // get additional permissions
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        // Storage Permissions
        final int REQUEST_EXTERNAL_STORAGE = 1;
        final String[] PERMISSIONS_STORAGE = { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE };
        requestPermissions(PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
        // Workaround for FileUriExposedException in Android >= M
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
    }
    dlgBuilder = new AlertDialog.Builder(this);
    // get preferences
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    // register for later changes
    prefs.registerOnSharedPreferenceChangeListener(this);
    // Overlay feature has to be set before window content is set
    if (prefs.getBoolean(PREF_AUTOHIDE, false) && prefs.getBoolean(PREF_OVERLAY, false))
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
    // Set up all data adapters
    mPidAdapter = new ObdItemAdapter(this, R.layout.obd_item, ObdProt.PidPvs);
    mVidAdapter = new VidItemAdapter(this, R.layout.obd_item, ObdProt.VidPvs);
    mDfcAdapter = new DfcItemAdapter(this, R.layout.obd_item, ObdProt.tCodes);
    currDataAdapter = mPidAdapter;
    // get list view
    mListView = getWindow().getLayoutInflater().inflate(R.layout.obd_list, null);
    // update all settings from preferences
    onSharedPreferenceChanged(prefs, null);
    // set up logging ...
    String logFileName = FileHelper.getPath(this).concat(File.separator).concat("log");
    try {
        // ensure log directory is available
        new File(logFileName).mkdirs();
        // Create new log file handler (max. 250 MB, 5 files rotated, non appending)
        logFileHandler = new FileHandler(logFileName.concat("/AndrOBD.log.%g.txt"), 250 * 1024 * 1024, 5, false);
        // Set log message formatter
        logFileHandler.setFormatter(new SimpleFormatter() {

            String format = "%1$tF\t%1$tT.%1$tL\t%4$s\t%3$s\t%5$s%n";

            @Override
            public synchronized String format(LogRecord lr) {
                return String.format(format, new Date(lr.getMillis()), lr.getSourceClassName(), lr.getLoggerName(), lr.getLevel().getLocalizedName(), lr.getMessage());
            }
        });
        // add file logging ...
        Logger.getLogger("").addHandler(logFileHandler);
        // set
        setLogLevels();
    } catch (IOException e) {
        // try to log error (at least with system logging)
        log.log(Level.SEVERE, logFileName, e);
    }
    // Log program startup
    log.info(String.format("%s %s starting", getString(R.string.app_name), getString(R.string.app_version)));
    // create file helper instance
    fileHelper = new FileHelper(this, CommService.elm);
    // set listeners for data structure changes
    setDataListeners();
    // automate elm status display
    CommService.elm.addPropertyChangeListener(this);
    // set up action bar
    ActionBar actionBar = getActionBar();
    if (actionBar != null) {
        actionBar.setDisplayShowTitleEnabled(true);
    }
    // start automatic toolbar hider
    setAutoHider(prefs.getBoolean(PREF_AUTOHIDE, false));
    // set content view
    setContentView(R.layout.startup_layout);
    // override comm medium with USB connect intent
    if ("android.hardware.usb.action.USB_DEVICE_ATTACHED".equals(getIntent().getAction())) {
        CommService.medium = CommService.MEDIUM.USB;
    }
    switch(CommService.medium) {
        case BLUETOOTH:
            // Get local Bluetooth adapter
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            log.fine("Adapter: " + mBluetoothAdapter);
            // If BT is not on, request that it be enabled.
            if (getMode() != MODE.DEMO && mBluetoothAdapter != null) {
                // remember initial bluetooth state
                initialBtStateEnabled = mBluetoothAdapter.isEnabled();
                if (!initialBtStateEnabled) {
                    Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
                }
            }
            break;
        case USB:
        case NETWORK:
            setMode(MODE.ONLINE);
            break;
    }
}
Also used : AlertDialog(android.app.AlertDialog) SimpleFormatter(java.util.logging.SimpleFormatter) Intent(android.content.Intent) IOException(java.io.IOException) Date(java.util.Date) FileHandler(java.util.logging.FileHandler) StrictMode(android.os.StrictMode) LogRecord(java.util.logging.LogRecord) File(java.io.File) ActionBar(android.app.ActionBar)

Example 69 with SimpleFormatter

use of java.util.logging.SimpleFormatter in project org.csstudio.display.builder by kasemir.

the class CommandExecutorTest method setupLogger.

public void setupLogger() {
    // 1-date, 2-source, 3-logger, 4-level, 5-message, 6-thrown
    System.setProperty("java.util.logging.SimpleFormatter.format", "%4$s: %5$s\n");
    log_buf = new ByteArrayOutputStream();
    handler = new StreamHandler(log_buf, new SimpleFormatter());
    logger.addHandler(handler);
}
Also used : StreamHandler(java.util.logging.StreamHandler) SimpleFormatter(java.util.logging.SimpleFormatter) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Example 70 with SimpleFormatter

use of java.util.logging.SimpleFormatter in project vespa by vespa-engine.

the class LogFileHandlerTestCase method testSimpleLogging.

@Test
public void testSimpleLogging() {
    String logFilePattern = "./testLogFileG1.txt";
    // create logfilehandler
    LogFileHandler h = new LogFileHandler();
    h.setFilePattern(logFilePattern);
    h.setFormatter(new SimpleFormatter());
    h.setRotationTimes("0 5 ...");
    // write log
    LogRecord lr = new LogRecord(Level.INFO, "testDeleteFileFirst1");
    h.publish(lr);
    h.flush();
    new File(logFilePattern).deleteOnExit();
}
Also used : LogRecord(java.util.logging.LogRecord) SimpleFormatter(java.util.logging.SimpleFormatter) LogFileHandler(com.yahoo.container.logging.LogFileHandler) File(java.io.File) Test(org.junit.Test)

Aggregations

SimpleFormatter (java.util.logging.SimpleFormatter)100 FileHandler (java.util.logging.FileHandler)59 Logger (java.util.logging.Logger)36 File (java.io.File)28 Handler (java.util.logging.Handler)23 IOException (java.io.IOException)17 StreamHandler (java.util.logging.StreamHandler)16 Properties (java.util.Properties)15 ByteArrayOutputStream (java.io.ByteArrayOutputStream)14 LogRecord (java.util.logging.LogRecord)13 BalancerRunner (org.mobicents.tools.sip.balancer.BalancerRunner)13 Config (edu.neu.ccs.pyramid.configuration.Config)11 ConsoleHandler (java.util.logging.ConsoleHandler)10 Formatter (java.util.logging.Formatter)9 Test (org.junit.Test)7 MockResponse (com.google.mockwebserver.MockResponse)6 HttpClient (org.apache.http.client.HttpClient)6 HttpGet (org.apache.http.client.methods.HttpGet)6 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)6 Pair (edu.neu.ccs.pyramid.util.Pair)3