Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Maintenance: Add internal Logging capabilities using zhttp.log #1115

Merged
merged 136 commits into from
May 25, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
136 commits
Select commit Hold shift + click to select a range
7d6457d
implemented logging configuration to be able to invesigate netty laye…
gciuloaica Feb 28, 2022
3a32285
the low level logger should be off by default. logback config should …
gciuloaica Feb 28, 2022
d72adf8
wip
gciuloaica Feb 28, 2022
59b4b26
using internal logging
gciuloaica Mar 2, 2022
61140bd
Merge branch 'main' of github.com:dream11/zio-http into netty-logger-…
gciuloaica Mar 3, 2022
250523c
implemented simple console logging that is not allocated any memory f…
gciuloaica Mar 4, 2022
7d89f28
improved the logging api
gciuloaica Mar 4, 2022
869e9fc
udated workflow and added more logging
gciuloaica Mar 4, 2022
3177ff3
removed unused file
gciuloaica Mar 7, 2022
fd4cfc0
removed unused code.
gciuloaica Mar 9, 2022
2fe1737
extended loggig settings in configuration to provide ability to set d…
gciuloaica Mar 17, 2022
05e1118
added more logging and set benchmark in DEBBUG mode.
gciuloaica Mar 21, 2022
50f1ca6
Merge branch 'main' of github.com:dream11/zio-http into netty-logger-…
gciuloaica Mar 21, 2022
644da73
fixed merge
gciuloaica Mar 21, 2022
0293625
fixed formatting
gciuloaica Mar 21, 2022
2bd102e
changed logging level to INFO
gciuloaica Mar 21, 2022
4c80f23
change logging level for confing details
gciuloaica Mar 21, 2022
ca9f9ac
Merge branch 'main' of github.com:dream11/zio-http into netty-logger-…
gciuloaica Mar 21, 2022
5d2e103
disabled logging from benchmark
gciuloaica Mar 21, 2022
1d8321e
Merge branch 'main' of github.com:dream11/zio-http into netty-logger-…
gciuloaica Mar 28, 2022
e51386e
Merge branch 'main' of github.com:dream11/zio-http into netty-logger-…
gciuloaica Apr 8, 2022
581256c
doc: add scala dzio-http/src/test/scala/zhttp/internal/HttpGen.scalaoc
tusharmath Apr 9, 2022
b41e36b
remove: support logging of throwable
tusharmath Apr 9, 2022
a9831cd
refactor: rename params
tusharmath Apr 9, 2022
6a33bba
refactor: reorder methods
tusharmath Apr 9, 2022
eb2610c
refactor: Move ConsoleLogger into LogFrontend
tusharmath Apr 9, 2022
343fef0
refactor: Simplify LoggerFactory
tusharmath Apr 10, 2022
66db2c2
refactor: use `Logger.make` for generating a Logger
tusharmath Apr 10, 2022
919c91c
refactor: simplify LoggerMacro for 2.13
tusharmath Apr 10, 2022
a02bdae
refactor: simplify LogFrontend
tusharmath Apr 10, 2022
6b378b6
refactor: move LogLine inside of LogFormat
tusharmath Apr 10, 2022
33e470a
refactor: add apply method on LogFormat
tusharmath Apr 10, 2022
35ebba4
refactor: add LogTransport
tusharmath Apr 10, 2022
9896287
refactor: add Glogger
tusharmath Apr 11, 2022
88da3d8
working version after refactoring
gciuloaica Apr 18, 2022
2593d32
Merge branch 'main' of github.com:dream11/zio-http into netty-logger-…
gciuloaica Apr 18, 2022
54014c5
more refactoring
gciuloaica Apr 19, 2022
7850341
added location information, from where the log has been invoked
gciuloaica Apr 19, 2022
1215d6e
Merge branch 'netty-logger-zhttp' of github.com:dream11/zio-http into…
gciuloaica Apr 19, 2022
b004060
fixed after merge
gciuloaica Apr 19, 2022
6b3de8c
fixed scala 2.12 compilation
gciuloaica Apr 19, 2022
e07de8f
Merge branch 'main' of github.com:dream11/zio-http into netty-logger-…
gciuloaica Apr 19, 2022
b141eb8
migrating scala 3 macro wip
gciuloaica Apr 21, 2022
170d8b5
re-implemented based on new design. Single LoggerTransport for now is…
gciuloaica Apr 21, 2022
e1f2bf6
refactor: removed InternalLogger and the macro sbt package
gciuloaica Apr 26, 2022
d148dd3
Merge branch 'main' of github.com:dream11/zio-http into netty-logger-…
gciuloaica Apr 26, 2022
6ad62b5
wip adding another transport
gciuloaica Apr 26, 2022
ab55020
updated ci workflow
gciuloaica Apr 26, 2022
26f99fd
fixed scala 3 macro
gciuloaica Apr 26, 2022
6d67f5a
formatted
gciuloaica Apr 26, 2022
8a7a176
fixed scala 3 macro
gciuloaica Apr 26, 2022
5fa3756
removed compiler warning for scala 3
gciuloaica Apr 27, 2022
051956b
more simplifications
gciuloaica Apr 27, 2022
35ccd7a
added file transport implementation
gciuloaica Apr 27, 2022
e326704
added integration tests
gciuloaica Apr 27, 2022
7ea75c0
updated usage of logger in zio-http
gciuloaica Apr 27, 2022
9c38a47
updated tests to use api for java 8 only, added tags support in LogFo…
gciuloaica Apr 27, 2022
1b8f966
updated test to work also with scala 2.12
gciuloaica Apr 27, 2022
1006647
more simplifications
gciuloaica Apr 28, 2022
c67703b
fixed imports
gciuloaica Apr 28, 2022
ff6380f
updated server API to allow users of the API to provide a custom logger
gciuloaica Apr 28, 2022
cbf02b0
more simplifications - the name of the logger was redundant as we hav…
gciuloaica Apr 28, 2022
f02bcb0
updated example and added more log to server implementation
gciuloaica Apr 28, 2022
16f97e0
undo the exmple changes
gciuloaica Apr 29, 2022
da7ac32
Merge branch 'main' into netty-logger-zhttp
tusharmath Apr 30, 2022
3d86d15
refactor: rename logLevels
tusharmath Apr 30, 2022
46c817d
refactor: make LoggerFactory.Live private
tusharmath Apr 30, 2022
115567b
refactor: clean up the logger a bit
tusharmath Apr 30, 2022
33d249e
refactor: make LogTransport private to Logger
tusharmath Apr 30, 2022
40bda22
doc: add scala doc in netty logger
tusharmath Apr 30, 2022
e787248
doc: update scala doc
tusharmath Apr 30, 2022
25e5e3e
chore: remove unnecessary build changes
tusharmath Apr 30, 2022
644acca
refactor: LogFrontend and LoggerTransport
tusharmath Apr 30, 2022
50cc723
style: fmt
amitksingh1490 May 1, 2022
a5b1617
feature: add `autodetectLevel` and `startsWith` operators on Logger
tusharmath Apr 30, 2022
a0728fc
feat: add `detectFromEnv` method to LogLevel
tusharmath May 1, 2022
fde19e7
refactor: update Scala doc from Logger.scala
tusharmath May 1, 2022
dd31254
refactor: disable logging by default while reading loglevel from env
tusharmath May 1, 2022
af4f5a8
refactor: rename file
tusharmath May 1, 2022
7c6c023
refactor: simplify LogTransport
tusharmath May 1, 2022
040b8dc
feature: add `dispatch` and operators to modify tags
tusharmath May 1, 2022
fc217e6
perf: optimize Logger's macro implementation
tusharmath May 1, 2022
c82e503
Merge branch 'netty-logger-zhttp' of github.com:dream11/zio-http into…
gciuloaica May 4, 2022
1887535
scala 3 macro fixes and other cosmetic changes
gciuloaica May 4, 2022
fcca862
logger transport will discard the log line based on log transport log…
gciuloaica May 4, 2022
a9b2b4e
used SourcePos instead of passing 2 values around, only trace will pr…
gciuloaica May 6, 2022
040a75a
fixed flaky test
gciuloaica May 6, 2022
12c9475
style: reorder methods in Server
tusharmath May 8, 2022
6727c54
Merge branch 'main' into netty-logger-zhttp
tusharmath May 8, 2022
2e5311f
feature: add More LogDetection logic
tusharmath May 8, 2022
d3c8e19
refactor: drop `tags` from LogStatement
tusharmath May 8, 2022
79eada6
feature: add splat operator for withTags
tusharmath May 8, 2022
3b1bbc7
refactor: add `detechLevelFromProps`
tusharmath May 8, 2022
50e520d
chore: update default app to HelloWorld
tusharmath May 8, 2022
c25675d
refactor: cleanup LogFormat
tusharmath May 8, 2022
f390685
refactor: remove redundant `withTag` operator
tusharmath May 8, 2022
c7e9dbc
refactor: cleanup log statements in Server
tusharmath May 8, 2022
396c4e0
performance: optimize scala 3 output
tusharmath May 9, 2022
ff65e41
removed logging from API. the Log instance is created with LogLevel r…
gciuloaica May 11, 2022
f709b5e
formatting
gciuloaica May 11, 2022
5ecddaa
formatting
gciuloaica May 11, 2022
1e38cab
more tests for logger using an in memory transport
gciuloaica May 13, 2022
af59da4
fixed for scala 2.12
gciuloaica May 13, 2022
951b2cb
fix for scala 3
gciuloaica May 13, 2022
20ec5f5
removed logger api documentation
gciuloaica May 13, 2022
8c058cb
added empty line
gciuloaica May 13, 2022
d8ed1d9
update log tests
gciuloaica May 13, 2022
201ee8d
macro updated to check if the level is enabled for a certain log level
gciuloaica May 13, 2022
bb9da9d
trading maintenability for performance: extended LoggerMacroExtension…
gciuloaica May 16, 2022
0c07155
added isEnabled flag in logger
gciuloaica May 18, 2022
11f4a58
Merge branch 'main' into netty-logger-zhttp
tusharmath May 19, 2022
04a6725
chore: set default LogLevel to INFO
tusharmath May 19, 2022
a9a93d4
style: remove unnecessary bracket
tusharmath May 19, 2022
fdcd6f8
refactor: add Logging.scala
tusharmath May 19, 2022
ac71a76
refactor: update ChannelInitializer LogStatement
tusharmath May 19, 2022
aaebf84
refactor: Update log statement inside of runtime
tusharmath May 19, 2022
79b8746
refactor: Change default LogLevel to `Error`
tusharmath May 19, 2022
b293346
refactor: use `SimpleName` for class names
tusharmath May 19, 2022
f202e8e
formatting
gciuloaica May 19, 2022
62e9bf0
removed debug log statements.
gciuloaica May 19, 2022
8778244
rolled back last change
gciuloaica May 19, 2022
20bef93
minor correction in test name
gciuloaica May 19, 2022
42f6d3c
short circuit the logl level cheks when logger is disabled
gciuloaica May 19, 2022
c559265
refactor: add more operators to compare LogLevel
tusharmath May 19, 2022
0774d5a
chore: update scala-settings to ignore unused parameters
tusharmath May 19, 2022
079cbd8
refactor: add detectedLogLevel
tusharmath May 20, 2022
918d1ed
refactor: change dispatch signature
tusharmath May 20, 2022
6175b1b
refactor: add tests for LogLevel
tusharmath May 21, 2022
adfcbd1
refactor: rename formats
tusharmath May 21, 2022
0bc4ab1
refactor: clean-up logLevel
tusharmath May 21, 2022
e211b49
refactor: drop `Disable` level for Logging
tusharmath May 21, 2022
842b367
refactor: LoggerTransport to become an abstract class
tusharmath May 21, 2022
f9ac266
refactor: simplify LoggerSpec
tusharmath May 21, 2022
261832f
chore: update build
tusharmath May 21, 2022
512bea0
chore: update ScalaSettings
tusharmath May 25, 2022
0029336
if the env value is not matching any defined log levels, than the log…
gciuloaica May 25, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ jobs:
run: sbt ++2.13.8 doc

- name: Compress target directories
run: tar cf targets.tar target zio-http-test/target zio-http/target zio-http-benchmarks/target example/target project/target
run: tar cf targets.tar target zio-http-test/target zio-http/target zio-http-benchmarks/target zio-http-logging/target example/target project/target

- name: Upload target directories
uses: actions/upload-artifact@v2
Expand Down
22 changes: 21 additions & 1 deletion build.sbt
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import BuildHelper._
import Dependencies._
import sbt.librarymanagement.ScalaArtifacts.isScala3

val releaseDrafterVersion = "5"

// Setting default log level to INFO
val _ = sys.props += ("ZHttpLogLevel" -> "INFO")

// CI Configuration
ThisBuild / githubWorkflowJavaVersions := Seq(JavaSpec.graalvm("21.1.0", "11"), JavaSpec.temurin("8"))
ThisBuild / githubWorkflowPREventTypes := Seq(
Expand Down Expand Up @@ -86,6 +90,7 @@ lazy val root = (project in file("."))
zhttp,
zhttpBenchmarks,
zhttpTest,
zhttpLogging,
example,
)

Expand All @@ -104,6 +109,7 @@ lazy val zhttp = (project in file("zio-http"))
`scala-compact-collection`,
),
)
.dependsOn(zhttpLogging)

lazy val zhttpBenchmarks = (project in file("zio-http-benchmarks"))
.enablePlugins(JmhPlugin)
Expand All @@ -117,9 +123,23 @@ lazy val zhttpTest = (project in file("zio-http-test"))
.settings(stdSettings("zhttp-test"))
.settings(publishSetting(true))

lazy val zhttpLogging = (project in file("zio-http-logging"))
.settings(stdSettings("zhttp-logging"))
.settings(publishSetting(false))
.settings(
libraryDependencies ++= {
if (isScala3(scalaVersion.value)) Seq.empty
else Seq(reflect.value % Provided)
},
)
gciuloaica marked this conversation as resolved.
Show resolved Hide resolved
.settings(
testFrameworks += new TestFramework("zio.test.sbt.ZTestFramework"),
libraryDependencies ++= Seq(`zio-test`, `zio-test-sbt`),
)

lazy val example = (project in file("./example"))
.settings(stdSettings("example"))
.settings(publishSetting(false))
.settings(runSettings("example.Main"))
.settings(runSettings("example.HelloWorld"))
.settings(libraryDependencies ++= Seq(`jwt-core`))
.dependsOn(zhttp)
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package example

import io.netty.util.AsciiString
import zhttp.http.{Http, _}
import zhttp.http._
import zhttp.service.server.ServerChannelFactory
import zhttp.service.{EventLoopGroup, Server}
import zio.{App, ExitCode, UIO, URIO}
Expand Down
49 changes: 10 additions & 39 deletions project/BuildHelper.scala
Original file line number Diff line number Diff line change
Expand Up @@ -24,40 +24,11 @@ object BuildHelper extends ScalaSettings {
}
}

private val std2xOptions = Seq(
"-language:higherKinds",
"-language:existentials",
"-explaintypes",
"-Yrangepos",
"-Xlint:_,-missing-interpolator,-type-parameter-shadow",
"-Ywarn-numeric-widen",
"-Ywarn-macros:after",
)

private def optimizerOptions(optimize: Boolean) =
if (optimize)
Seq(
"-opt:l:inline",
)
else Nil

def extraOptions(scalaVersion: String, optimize: Boolean) =
def extraOptions(scalaVersion: String) =
CrossVersion.partialVersion(scalaVersion) match {
case Some((3, 0)) =>
Seq(
"-language:implicitConversions",
"-Xignore-scala2-macros",
"-noindent",
)
case Some((2, 12)) =>
Seq("-Ywarn-unused:params,-implicits") ++ std2xOptions
case Some((2, 13)) =>
Seq(
"-Ywarn-unused:params,-implicits",
"-Ywarn-macros:after",
"-Ywarn-value-discard",
) ++ std2xOptions ++ tpoleCatSettings ++
optimizerOptions(optimize)
case Some((3, 0)) => scala3Settings
case Some((2, 12)) => scala212Settings
case Some((2, 13)) => scala213Settings
case _ => Seq.empty
}

Expand All @@ -78,11 +49,11 @@ object BuildHelper extends ScalaSettings {
}

def stdSettings(prjName: String) = Seq(
name := s"$prjName",
ThisBuild / crossScalaVersions := Seq(Scala212, Scala213, ScalaDotty),
ThisBuild / scalaVersion := Scala213,
scalacOptions := stdOptions ++ extraOptions(scalaVersion.value, optimize = !isSnapshot.value),
semanticdbVersion := scalafixSemanticdb.revision, // use Scalafix compatible version
name := s"$prjName",
ThisBuild / crossScalaVersions := Seq(Scala212, Scala213, ScalaDotty),
ThisBuild / scalaVersion := Scala213,
scalacOptions := stdOptions ++ extraOptions(scalaVersion.value),
semanticdbVersion := scalafixSemanticdb.revision, // use Scalafix compatible version
ThisBuild / scalafixScalaBinaryVersion := CrossVersion.binaryScalaVersion(scalaVersion.value),
ThisBuild / scalafixDependencies ++=
List(
Expand All @@ -92,7 +63,7 @@ object BuildHelper extends ScalaSettings {
Test / parallelExecution := true,
incOptions ~= (_.withLogRecompileOnMacro(false)),
autoAPIMappings := true,
ThisBuild / javaOptions := Seq("-Dio.netty.leakDetectionLevel=paranoid"),
ThisBuild / javaOptions := Seq("-Dio.netty.leakDetectionLevel=paranoid", "-DZHttpLogLevel=INFO"),
ThisBuild / fork := true,
)

Expand Down
3 changes: 3 additions & 0 deletions project/Dependencies.scala
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import sbt.Keys.scalaVersion
import sbt._

object Dependencies {
Expand Down Expand Up @@ -27,4 +28,6 @@ object Dependencies {
val `zio-streams` = "dev.zio" %% "zio-streams" % ZioVersion
val `zio-test` = "dev.zio" %% "zio-test" % ZioVersion % "test"
val `zio-test-sbt` = "dev.zio" %% "zio-test-sbt" % ZioVersion % "test"

val reflect = Def.map(scalaVersion)("org.scala-lang" % "scala-reflect" % _)
gciuloaica marked this conversation as resolved.
Show resolved Hide resolved
}
63 changes: 40 additions & 23 deletions project/ScalaSettings.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
trait ScalaSettings {
// RECOMMENDED SETTINGS: https://tpolecat.github.io/2017/04/25/scalac-flags.html
val tpoleCatSettings = Seq(
private val baseSettings = Seq(
"-language:postfixOps", // Added by @tusharmath
"-deprecation", // Emit warning and location for usages of deprecated APIs.
"-encoding",
Expand All @@ -25,27 +24,14 @@ trait ScalaSettings {
"-Xlint:private-shadow", // A private field (or class parameter) shadows a superclass field.
"-Xlint:stars-align", // Pattern sequence wildcard must align with sequence component.
"-Xlint:type-parameter-shadow", // A local type parameter shadows a type already in scope.
"-Xlint:unused", // TODO check if we still need -Wunused below
"-Xlint:nonlocal-return", // A return statement used an exception for flow control.
"-Xlint:implicit-not-found", // Check @implicitNotFound and @implicitAmbiguous messages.
"-Xlint:serial", // @SerialVersionUID on traits and non-serializable classes.
"-Xlint:valpattern", // Enable pattern checks in val definitions.
"-Xlint:eta-zero", // Warn on eta-expansion (rather than auto-application) of zero-ary method.
"-Xlint:eta-sam", // Warn on eta-expansion to meet a Java-defined functional interface that is not explicitly annotated with @FunctionalInterface.
"-Xlint:deprecation", // Enable linted deprecations.
"-Wdead-code", // Warn when dead code is identified.
"-Wextra-implicit", // Warn when more than one implicit parameter section is defined.
"-Wmacros:both", // Lints code before and after applying a macro
"-Wnumeric-widen", // Warn when numerics are widened.
"-Woctal-literal", // Warn on obsolete octal syntax.
"-Wunused:imports", // Warn if an import selector is not referenced.
"-Wunused:patvars", // Warn if a variable bound in a pattern is unused.
"-Wunused:privates", // Warn if a private member is unused.
"-Wunused:locals", // Warn if a local definition is unused.
"-Wunused:explicits", // Warn if an explicit parameter is unused.
"-Wunused:params", // Enable -Wunused:explicits,implicits.
"-Wunused:linted",
"-Wvalue-discard", // Warn when non-Unit expression results are unused.
// "-Xlint:unused", // TODO check if we still need -Wunused below

"-Xlint:deprecation", // Enable linted deprecations.

// "-Wunused:explicits", // Warn if an explicit parameter is unused.
// "-Wunused:params", // Enable -Wunused:explicits,implicits.
// "-Wunused:linted",

"-Ybackend-parallelism",
"8", // Enable paralellisation — change to desired number!
"-Ycache-plugin-class-loader:last-modified", // Enables caching of classloaders for compiler plugins
Expand All @@ -57,4 +43,35 @@ trait ScalaSettings {
// "-language:experimental.macros", // Allow macro definition (besides implementation and application). Disabled, as this will significantly change in Scala 3
// "-language:implicitConversions", // Allow definition of implicit functions called views. Disabled, as it might be dropped in Scala 3. Instead use extension methods (implemented as implicit class Wrapper(val inner: Foo) extends AnyVal {}
)

val scala3Settings: Seq[String] = Seq("-Xignore-scala2-macros", "-noindent")

// RECOMMENDED SETTINGS: https://tpolecat.github.io/2017/04/25/scalac-flags.html
val scala213Settings: Seq[String] = baseSettings ++ Seq(
"-Xlint:nonlocal-return", // A return statement used an exception for flow control.
"-Xlint:implicit-not-found", // Check @implicitNotFound and @implicitAmbiguous messages.
"-Xlint:serial", // @SerialVersionUID on traits and non-serializable classes.
"-Xlint:valpattern", // Enable pattern checks in val definitions.
"-Xlint:eta-zero", // Warn on eta-expansion (rather than auto-application) of zero-ary method.
"-Xlint:eta-sam", // Warn on eta-expansion to meet a Java-defined functional interface that is not explicitly annotated with @FunctionalInterface.
"-Wdead-code", // Warn when dead code is identified.
"-Wextra-implicit", // Warn when more than one implicit parameter section is defined.
"-Wmacros:after", // Lints code before and after applying a macro
"-Wnumeric-widen", // Warn when numerics are widened.
"-Woctal-literal", // Warn on obsolete octal syntax.
"-Wunused:imports", // Warn if an import selector is not referenced.
"-Wunused:patvars", // Warn if a variable bound in a pattern is unused.
"-Wunused:privates", // Warn if a private member is unused.
"-Wunused:locals", // Warn if a local definition is unused.
"-Wvalue-discard", // Warn when non-Unit expression results are unused.
)

val scala212Settings: Seq[String] = baseSettings ++ Seq(
"-explaintypes",
"-Yrangepos",
"-Xlint:_,-missing-interpolator,-type-parameter-shadow",
"-Ywarn-numeric-widen",
"-Ywarn-macros:after",
"-Ywarn-unused:-implicits",
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package zhttp.logging.macros

import zhttp.logging.macros.LoggerMacroImpl._

trait LoggerMacroExtensions { self =>
import scala.language.experimental.macros

val isDebugEnabled: Boolean
val isErrorEnabled: Boolean
val isInfoEnabled: Boolean
val isTraceEnabled: Boolean
val isWarnEnabled: Boolean

final def trace(msg: String): Unit = macro logTraceImpl
final def debug(msg: String): Unit = macro logDebugImpl
final def info(msg: String): Unit = macro logInfoImpl
final def warn(msg: String): Unit = macro logWarnImpl
final def error(msg: String): Unit = macro logErrorImpl
final def error(msg: String, throwable: Throwable): Unit =
macro logErrorWithCauseImpl
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package zhttp.logging.macros

import zhttp.logging.{LogLevel, Logger}

import scala.reflect.macros.whitebox

/**
* Macro inspired from log4s.
*/
private[zhttp] object LoggerMacroImpl {

/** A macro context that represents a method call on a Logger instance. */
private[this] type LogCtx = whitebox.Context { type PrefixType = Logger }

/**
* Log a message reflectively at a given level.
*/
private[this] def reflectiveLog(
c: LogCtx,
)(msg: c.Expr[String], error: Option[c.Expr[Throwable]])(logLevel: LogLevel) = {
import c.universe._
type Tree = c.universe.Tree

val cname: Tree = q"${c.internal.enclosingOwner.owner.fullName}"
val lno: Tree = q"${c.enclosingPosition.line}"
val sourceLocation: Tree =
if (logLevel == LogLevel.Trace)
q"Some(_root_.zhttp.logging.Logger.SourcePos($cname, $lno))"
else
q"None"
val logLevelName = logLevel.name.toLowerCase.capitalize
val level: Tree = q"_root_.zhttp.logging.LogLevel.${TermName(logLevelName)}"
val isEnabled: Tree = q"""${c.prefix.tree}.${TermName(s"is${logLevelName}Enabled")}"""

if (logLevel >= Logger.detectedLevel)
q"""
if($isEnabled) {
tusharmath marked this conversation as resolved.
Show resolved Hide resolved
val logMsg = ${msg.tree}
${c.prefix.tree}.dispatch(logMsg, $level, $error, ${sourceLocation})
}
"""
else q"()"
}

def logTraceImpl(c: LogCtx)(msg: c.Expr[String]): c.universe.Tree =
reflectiveLog(c)(msg, None)(LogLevel.Trace)

def logInfoImpl(c: LogCtx)(msg: c.Expr[String]): c.universe.Tree =
reflectiveLog(c)(msg, None)(LogLevel.Info)

def logDebugImpl(c: LogCtx)(msg: c.Expr[String]): c.universe.Tree =
reflectiveLog(c)(msg, None)(LogLevel.Debug)

def logWarnImpl(c: LogCtx)(msg: c.Expr[String]): c.universe.Tree =
reflectiveLog(c)(msg, None)(LogLevel.Warn)

def logErrorImpl(c: LogCtx)(msg: c.Expr[String]): c.universe.Tree =
reflectiveLog(c)(msg, None)(LogLevel.Error)

def logErrorWithCauseImpl(c: LogCtx)(msg: c.Expr[String], throwable: c.Expr[Throwable]): c.universe.Tree =
reflectiveLog(c)(msg, Some(throwable))(LogLevel.Error)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package zhttp.logging.macros

import zhttp.logging.Logger
import zhttp.logging.macros.LoggerMacroImpl._

/**
* Core Logger class.
*/
trait LoggerMacroExtensions{ self: Logger =>
import scala.language.experimental.macros

val isDebugEnabled: Boolean
val isErrorEnabled: Boolean
val isInfoEnabled: Boolean
val isTraceEnabled: Boolean
val isWarnEnabled: Boolean

inline def trace(inline msg: String): Unit = $ { logTraceImpl('self, 'msg) }
inline def debug(inline msg: String): Unit = $ { logDebugImpl('self, 'msg) }
inline def info(inline msg: String): Unit = $ { logInfoImpl('self, 'msg) }
inline def warn(inline msg: String): Unit = $ { logWarnImpl('self, 'msg) }
inline def error(inline msg: String): Unit = $ { logErrorImpl('self, 'msg) }
inline def error(inline msg: String, throwable: Throwable): Unit = ${logErrorWithCauseImpl('self, 'throwable, 'msg)}
}
Loading