aboutsummaryrefslogtreecommitdiff
path: root/src/main/scala/xyz/driver/core/logging/phiLogging.scala
blob: 27b6ddc2cb278ec513a6ef72f5ff96d2b6f26448 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package xyz.driver.core.logging

import java.time.{LocalDateTime, ZoneId}

import org.slf4j.LoggerFactory
import xyz.driver.core.Id
import xyz.driver.core.auth.User
import xyz.driver.core.logging.phi._

trait PhiSafeLogger {

  def error(message: NoPhiString): Unit

  def warn(message: NoPhiString): Unit

  def info(message: NoPhiString): Unit

  def debug(message: NoPhiString): Unit

  def trace(message: NoPhiString): Unit

}

class DefaultPhiSafeLogger(underlying: org.slf4j.Logger) extends PhiSafeLogger {

  def error(message: NoPhiString): Unit = underlying.error(message.text)

  def warn(message: NoPhiString): Unit = underlying.warn(message.text)

  def info(message: NoPhiString): Unit = underlying.info(message.text)

  def debug(message: NoPhiString): Unit = underlying.debug(message.text)

  def trace(message: NoPhiString): Unit = underlying.trace(message.text)

}

trait PhiSafeLogging {

  protected val logger: PhiSafeLogger = new DefaultPhiSafeLogger(LoggerFactory.getLogger(getClass.getName))

  /**
    * Logs the failMessage on an error level, if isSuccessful is false.
    * @return isSuccessful
    */
  protected def loggedError(isSuccessful: Boolean, failMessage: NoPhiString): Boolean = {
    if (!isSuccessful) {
      logger.error(failMessage)
    }
    isSuccessful
  }

  protected def logTime(userId: Id[User], label: NoPhiString, obj: NoPhiString): Unit = {
    val now = LocalDateTime.now(ZoneId.of("Z"))
    logger.info(noPhi"User id=${NoPhi(userId)} performed an action at $label=$now with a $obj")
  }
}