Giter Site home page Giter Site logo

jokade / slogging Goto Github PK

View Code? Open in Web Editor NEW
49.0 7.0 11.0 116 KB

A Typesafe-logging (and slf4j) compatible logging library based on macros for Scala/JVM, Scala.js, and Scala Native

License: MIT License

Scala 99.69% HTML 0.31%
scala slf4j scala-js log-statements scala-native

slogging's Introduction

slogging

A simple logging library for Scala, Scala.js, and Scala Native. Slogging is compatible to the scala-logging (and slf4j) API, and uses macros to check if logging statements should be executed.

News: Version 0.6.2 has been released (release notes)!

Contents:

Getting Started

SBT Settings

Add one of the following lines to your build.sbt (depending on your target):

Scala/JVM with logging to stdout:

libraryDependencies += "biz.enef" %% "slogging" % "0.6.2"

with slf4j:

libraryDependencies ++= Seq(
  "biz.enef" %% "slogging-slf4j" % "0.6.2",
  "org.slf4j" % "slf4j-simple" % "1.7.+"  // or another slf4j implementation
)

Scala.js with logging to console:

libraryDependencies += "biz.enef" %%% "slogging" % "0.6.2"

with winston (Node.js):

libraryDependencies += "biz.enef" %%% "slogging-winston" % "0.6.2"

with remote logging via HTTP POST:

libraryDependencies += "biz.enef" %%% "slogging-http" % "0.6.2"

Scala Native with logging to stderr:

libraryDependencies += "biz.enef" %%% "slogging" % "0.6.2"

with logging to syslogd:

libraryDependencies += "biz.enef" %%% "slogging-syslog" % "0.6.2"

with logging to GLib:

libraryDependencies += "biz.enef" %%% "slogging-glib" % "0.6.2"

slogging 0.6.2 is published for both Scala 2.12.x and Scala 2.13.x, Scala.js 1.0, and Scala Native 0.3.9 / 0.4.0-M2.

Logging and Configuration

Add logging statements

Mix one of two traits into your class/object to give it logging capability:

  • StrictLogging: the logger is initialized when the instance is created
  • LazyLogging: the logger is initialized on first access

Example:

import slogging.LazyLogging

class Foo extends LazyLogging {
  def bar() {
    // log an error message
    logger.error("...")
    // log a warning
    logger.warn("...")
    // log an info message
    logger.info("...")
    // log a debug message
    logger.debug("...")
    // log a tracing message
    logger.trace("...")
    // log a parameterized message
    logger.info("foo={}, bar={}",1,true)
  }
}

Activate logging and set log level

The default logger is a NullLogger which simply ignores all logging statements. To activate logging output, assign a different logger factory to LoggerConfig.factory, or call the apply() method of the logger factory you want to use. Assign a new value to LoggerConfig.level to change the current log level. Example:

import slogging._

object Main extends App {
  // select logger backend, e.g. simple logging using println (supported by Scala/JVM, Scala.js, and Scala Native) 
  LoggerConfig.factory = PrintLoggerFactory()

  // set log level, e.g. to DEBUG
  LoggerConfig.level = LogLevel.DEBUG
}

Note: Some backends (slf4j, winston) have their own log level management, which needs to be adjusted as well.

Disable logging at compile time

It is possible to omit logging statements from the generated code altogether. To this end add the following flag to your build.sbt:

scalacOptions += "-Xmacro-settings:slogging.disable"

FilterLogger

Sometimes it is useful to enable detailed logging (e.g. LogLevel.TRACE) only for some classes. This can be achieved using FilterLoggerFactory and setting FilterLogger.filter to a custom filter PartialFunction. The filter function receives a tuple (LogLevel.Value,String) that contains the log level and logger source name for every logging message; it must return the UnderlyingLogger instance to be used for this logging statement (and must be defined for every input, so make sure to provide a default case):

import slogging._

LoggerConfig.factory = FilterLoggerFactory()
LoggerConfig.level = LogLevel.TRACE

FilterLogger.filter = {
  // use PrintLogger for all trace statements from sources starting with "foo.bar"
  case (LogLevel.TRACE,source) if source.startsWith("foo.bar") => PrintLogger
  // ignore all other trace statements
  case (LogLevel.TRACE,_) => NullLogger
  // log all other levels
  case _ => PrintLogger
}

Note: The filter function is called after the current value of LoggerConfig.level has been checked. Hence, even if you want to log TRACE statements for a specific source using FilterLogger, you need to set FilterConfig.level = LogLevel.TRACE. This also means that all TRACE logging statements in the code are executed, even if they are subsequently discarded by NullLogger, which may have a serious impact on performance.

Backends

PrintLogger

This simple backend prints all messages to stderr (or stdout) and can be used with JVM, JS an Scala Native projects.

Usage:

// build.sbt
libraryDependencies += "biz.enef" %% "slogging" % "VERSION"
import slogging._

// activate PrintLogger
LoggerConfig.factory = PrintLoggerFactory()

// set this to activate timestamp logging
PrintLogger.printTimestamp = true

You can change the output stream to which messages are logged for each level, e.g.:

// use stderr for ERROR and WARN
PrintLoggerFactory.errorStream = System.err
PrintLoggerFactory.warnStream = System.err

// use stdout for all other levels
PrintLoggerFactory.infoStream = System.out
PrintLoggerFactory.debugStream = System.out
PrintLoggerFactory.traceStream = System.out

Furthermore, you may also change the format of logging message by providing a custom MessageFormatter:

object CustomFormatter extends MessageFormater {
  def formatMessage(level: MessageLevel, name: String, msg: String, cause: Option[Throwable]): String = {
    /* ... */
  }
}

PrintLoggerFactory.formatter = CustomFormatter

Scala / JVM

slogging supports the following logger backends on Scala (JVM):

SLF4JLoggerFactory

This backend is just a wrapper around slf4j.

Usage:

// build.sbt
libraryDependencies ++= Seq(
  "biz.enef" %% "slogging-slf4j" % "VERSION",
  "org.slf4j" % "slf4j-simple" % "1.7.+"  // or another slf4j implementation
)
import slogging._

// activate SLF4J backend
LoggerConfig.factory = SLF4JFactory()

Scala.js

slogging support the following logger backends for Scala.js:

ConsoleLoggerFactory

Similar to PrintLoggerFactory, but uses console.log instead of println().

Usage:

// build.sbt
libraryDependencies += "biz.enef" %%% "slogging" % "VERSION"
import slogging._

// activate ConsoleLogger; no additional configuration required
LoggerConfig.factory = ConsoleLoggerFactory()

WinstonLoggerFactory

A wrapper around the winston logging library for Node.js.

Usage:

// build.sbt
libraryDependencies += "biz.enef" %%% "slogging-winston" % "VERSION"

// activate module support to load winston module
scalaJSModuleKind := ModuleKind.CommonJSModule
import slogging._

// use default winston logger
LoggerConfig.factory = WinstonLoggerFactory()

// use a custom winston logger
import WinstonLoggerFactory.{WinstonLogger, winston}

LoggerConfig.factory = WinstonLoggerFactory(WinstonLogger(literal(
  levels = js.Dictionary(
    "trace" -> 0,
    "debug" -> 1,
    "info"  -> 2,
    "warn"  -> 3,
    "error" -> 4
  ),
  transports = js.Array(
    js.Dynamic.newInstance(winston.transports.Console)(literal(
      level = "debug"
    ))
  )
)))

HttpLoggerFactory

This backend sends log messages to a HTTP server via Ajax POST requests. Note that the same origin policy usually requires that the server to which the messages are sent must be the same server from which the javascript source was loaded.

Usage:

import slogging._

// function that assembles the JSON object to be sent
// (only required if you want to override the default formatter)
val fmt: HttpLoggerFactory.MessageFormatter = (clientId,level,name,msg,cause) => js.Dynamic.literal(
  id = clientId,
  loggerName = name,
  logMessage = msg
)

// configure & activate remote HTTP logging 
LoggerConfig.factory = 
  HttpLoggerFactory("/logging", // target URL for log messages
                    "client1",  // ID of the client that sends the messages (optional)
                    fmt         // message formatting function (optional)
                   ) 

Scala Native

slogging supports the following logger backends on Scala Native:

TerminalLogger

Logs all messages to stderr using fprintf. Messages are enclosed in ANSI terminal control codes, which can be configured separately for every level.

Usage:

// build.sbt
libraryDependencies += "biz.enef" %%% "slogging" % "VERSION"
// use default TerminalLogger
// (error messages are printed in red, warnings in yellow)
LoggerConfig.factory = TerminalLoggerFactory()

// print INFO messages in blue
TerminalLoggerFactory.infoCode = TerminalControlCode.blue

// change the message formatter
TerminalLoggerFactory.formatter = ...

SyslogLogger

This backend uses the standard syslog facility.

Usage:

// build.sbt
libraryDependencies += "biz.enef" %%% "slogging-syslog" % "VERSION"
LoggerConfig.factory = SyslogLoggerFactory()

GLibLogger

This backend uses GLib's g_log() to log messages, e.g. for use with scalanative-gtk.

Usage:

// build.sbt
libraryDependencies += "biz.enef" %%% "slogging-glib" % "VERSION"

nativeLinkingOptions += "-lglib-2.0" // you may need to change this depending on your glib installation
LoggerConfig.factory = GLibLoggerFactory()

// optionally change message formatter
GLibLoggerFactory.formatter = ...

License

This code is open source software licensed under the MIT License

slogging's People

Contributors

jokade avatar julienrf avatar lolgab avatar ricogit avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

slogging's Issues

Improve PrintLogger

  • support specification of PrintStream to be used for each level
  • support MessageFormatter

Update to Scala 2.13

Please publish artifacts for the latest Scala 2.13.0, it should be rather straightforward to update.

Provide a way to set the default logger via configuration or jvm args

The default logger defaults to NullLogger right now. We have backend code that uses slf4j and need a simple way to configure the SLF4JLoggerFactory backend when running in the JVM. This isn't as simple as putting a configuration point in a single place where our application starts. There are numerous other scenarios where we may not go through that entry point but still need our backend code to use the SLF4JLoggerFactory (unit tests, integ tests, console, dev main vs prod main, etc.)

We'd like to configure the slogging backend in a manner similar to what is done to configure Akka to use the slf4j logging backend which is to put an entry in our application.conf like:

slogging.backend = "slogging.SLF4JLoggerFactory"

Unfortunately that would mean that your slogging core would have to take a dependency on TypesafeConfig which probably isn't doable.

An alternative is to allow jvm args: -Dslogging.backend=slogging.SLF4JLoggerFactory

Change semantics of LoggerFactory.apply()

Currently, calling LoggerFactory.apply() assigns the LoggerFactory on which the call was made to LoggerConfig.factory. We need to remove this side effect in order to be able to build LoggerFactoryS that use other factories (e.g. a FilterLoggerFactory).

New semantics: calling LoggerFactory.apply() simply returns the default instance to be used; factories need to be assigned explicitly, i.e.:

LoggerConfig.factory = PrintLoggerFactory()

New release targetting Scala Native 0.4.0-M2

Even if SN 0.4.0-M2 is a milestone, it is quite stable and now used as a target for several projects.
It would thus be great to consider to release a version of slogging compatible with this Scala Native version.

Thanks.

Extract logging source name from logger instance

Instead of storing the logging source name in the logger instance this should be added as member to the LoggerHolder trait. This way we don't need to generate a logger instance for every LoggingHolder, and we can re-use logger instances in FilterLogger.filter functions.

Provide a FilterLoggerFactory

A FilterLogger uses a PartialFunction that receives the name of the logging source and the LogLevel, and returns the logger instance to be used to log the message.

PrintLogger.printTimestamp is missing from 0.6.1

Hello. Im having trouble using PrintLogger in a clean project as it does not have a field printTimestamp for some reason.

My build.sbt:

name := "loggingtest"
version := "0.1"
scalaVersion := "2.12.4"
libraryDependencies += "biz.enef" %% "slogging" % "0.6.1"

Main.scala:

import slogging._

object Main {

  def main(args: Array[String]): Unit = {

    LoggerConfig.factory = PrintLoggerFactory()
    LoggerConfig.level = LogLevel.TRACE

    PrintLogger.printTimestamp = true

  }
}

image

Can you please point me to the right direction? Maybe there is some conflict of versions in maven repository or something?

Sorry for a basic question, I dont really have a lot of experience with Scala environment and I can't figure out what might be the problem.

Add TerminalLogger

Provide a TerminalLogger with colored terminal output for scala-native

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.