remove log4j entirely

Wed, 15 Dec 2021 19:56:05 +0100

author
Mike Becker <universe@uap-core.de>
date
Wed, 15 Dec 2021 19:56:05 +0100
changeset 247
e71ae69c68c0
parent 246
9a81a11be70e
child 248
90dc13c78b5d

remove log4j entirely

build.gradle.kts file | annotate | diff | comparison | revisions
src/main/kotlin/de/uapcore/lightpit/AbstractServlet.kt file | annotate | diff | comparison | revisions
src/main/kotlin/de/uapcore/lightpit/DataSourceProvider.kt file | annotate | diff | comparison | revisions
src/main/kotlin/de/uapcore/lightpit/Logging.kt file | annotate | diff | comparison | revisions
src/main/kotlin/de/uapcore/lightpit/MyLogger.kt file | annotate | diff | comparison | revisions
src/main/kotlin/de/uapcore/lightpit/servlet/ProjectServlet.kt file | annotate | diff | comparison | revisions
src/main/kotlin/de/uapcore/lightpit/servlet/UsersServlet.kt file | annotate | diff | comparison | revisions
--- a/build.gradle.kts	Sun Dec 12 18:16:46 2021 +0100
+++ b/build.gradle.kts	Wed Dec 15 19:56:05 2021 +0100
@@ -7,8 +7,6 @@
 group = "de.uapcore"
 version = "0.6-SNAPSHOT"
 
-val log4jVersion = "2.15.0"
-val slf4jVersion = "1.7.30"
 val flexmarkVersion = "0.62.2"
 
 repositories {
@@ -36,9 +34,6 @@
             dependencies {
                 compileOnly("javax.servlet:javax.servlet-api:3.1.0")
                 compileOnly("javax.servlet:jstl:1.2")
-                implementation("org.slf4j:slf4j-api:${slf4jVersion}")
-                implementation("org.apache.logging.log4j:log4j-core:${log4jVersion}")
-                implementation("org.apache.logging.log4j:log4j-slf4j-impl:${log4jVersion}")
                 implementation("com.vladsch.flexmark:flexmark:${flexmarkVersion}")
                 implementation("com.vladsch.flexmark:flexmark-util-data:${flexmarkVersion}")
                 implementation("com.vladsch.flexmark:flexmark-ext-tables:${flexmarkVersion}")
--- a/src/main/kotlin/de/uapcore/lightpit/AbstractServlet.kt	Sun Dec 12 18:16:46 2021 +0100
+++ b/src/main/kotlin/de/uapcore/lightpit/AbstractServlet.kt	Wed Dec 15 19:56:05 2021 +0100
@@ -34,7 +34,9 @@
 import javax.servlet.http.HttpServletRequest
 import javax.servlet.http.HttpServletResponse
 
-abstract class AbstractServlet : LoggingTrait, HttpServlet() {
+abstract class AbstractServlet : HttpServlet() {
+    
+    protected val logger = MyLogger()
 
     /**
      * Contains the GET request mappings.
@@ -68,7 +70,7 @@
             Pair(PathPattern(requestPath), ::notFound)
         } else {
             if (candidates.size > 1) {
-                logger().warn("Ambiguous mapping for request path '{}'", requestPath)
+                logger.warn("Ambiguous mapping for request path '{0}'", requestPath)
             }
             candidates.entries.first().toPair()
         }
@@ -82,7 +84,7 @@
     ) {
         val params = mapping.first.obtainPathParameters(sanitizedRequestPath(req))
         val method = mapping.second
-        logger().trace("invoke {}", method)
+        logger.trace("invoke {0}", method)
         method(HttpRequest(req, resp, params), dao)
     }
 
@@ -105,13 +107,13 @@
             val sessionLocale = if (availableLanguages.contains(reqLocale)) reqLocale else availableLanguages.first()
             session.setAttribute(Constants.SESSION_ATTR_LANGUAGE, sessionLocale)
             resp.locale = sessionLocale
-            logger().debug(
-                "Setting language for new session {}: {}", session.id, sessionLocale.displayLanguage
+            logger.debug(
+                "Setting language for new session {0}: {1}", session.id, sessionLocale.displayLanguage
             )
         } else {
             val sessionLocale = session.getAttribute(Constants.SESSION_ATTR_LANGUAGE) as Locale
             resp.locale = sessionLocale
-            logger().trace("Continuing session {} with language {}", session.id, sessionLocale)
+            logger.trace("Continuing session {0} with language {1}", session.id, sessionLocale)
         }
 
         // set some internal request attributes
@@ -150,8 +152,8 @@
                     invokeMapping(findMapping(mappings, req), req, resp, dao)
                     connection.commit()
                 } catch (ex: SQLException) {
-                    logger().warn("Database transaction failed (Code {}): {}", ex.errorCode, ex.message)
-                    logger().debug("Details: ", ex)
+                    logger.warn("Database transaction failed (Code {0}): {1}", ex.errorCode, ex.message)
+                    logger.debug("Details: ", ex)
                     resp.sendError(
                         HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                         "Unhandled Transaction Error - Code: " + ex.errorCode
@@ -160,8 +162,8 @@
                 }
             }
         } catch (ex: SQLException) {
-            logger().error("Severe Database Exception (Code {}): {}", ex.errorCode, ex.message)
-            logger().debug("Details: ", ex)
+            logger.error("Severe Database Exception (Code {0}): {1}", ex.errorCode, ex.message)
+            logger.debug("Details: ", ex)
             resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database Error - Code: " + ex.errorCode)
         }
     }
--- a/src/main/kotlin/de/uapcore/lightpit/DataSourceProvider.kt	Sun Dec 12 18:16:46 2021 +0100
+++ b/src/main/kotlin/de/uapcore/lightpit/DataSourceProvider.kt	Wed Dec 15 19:56:05 2021 +0100
@@ -38,7 +38,9 @@
  * Provides access to the database.
  */
 @WebListener
-class DataSourceProvider : ServletContextListener, LoggingTrait {
+class DataSourceProvider : ServletContextListener {
+
+    private val logger = MyLogger()
 
     enum class Dialect {
         Postgres
@@ -100,7 +102,7 @@
                     )
                 }
                 val metaData = conn.metaData
-                logger().info(
+                logger.info(
                     "Connections as {} to {}/{} ready to go.",
                     metaData.userName,
                     metaData.url,
@@ -108,18 +110,18 @@
                 )
             }
         } catch (ex: SQLException) {
-            logger().error("Checking database connection failed", ex)
+            logger.error("Checking database connection failed", ex)
         }
     }
 
     private fun retrieveDataSource(ctx: Context): DataSource? {
         return try {
             val ret = ctx.lookup(DS_JNDI_NAME) as DataSource
-            logger().info("Data source retrieved.")
+            logger.info("Data source retrieved.")
             ret
         } catch (ex: NamingException) {
-            logger().error("Data source {} not available.", DS_JNDI_NAME)
-            logger().error("Reason for the missing data source: ", ex)
+            logger.error("Data source {0} not available.", DS_JNDI_NAME)
+            logger.error("Reason for the missing data source: ", ex)
             null
         }
     }
@@ -132,8 +134,8 @@
             try {
                 dialect = Dialect.valueOf(dbDialect)
             } catch (ex: IllegalArgumentException) {
-                logger().error(
-                    "Unknown or unsupported database dialect {}. Defaulting to {}.",
+                logger.error(
+                    "Unknown or unsupported database dialect {0}. Defaulting to {1}.",
                     dbDialect,
                     dialect
                 )
@@ -141,22 +143,22 @@
         }
 
         dataSource = try {
-            logger().debug("Trying to access JNDI context ...")
+            logger.debug("Trying to access JNDI context ...")
             val initialCtx: Context = InitialContext()
             val ctx = initialCtx.lookup("java:comp/env") as Context
             retrieveDataSource(ctx)
         } catch (ex: NamingException) {
-            logger().error("Cannot access JNDI resources.", ex)
+            logger.error("Cannot access JNDI resources.", ex)
             null
         } catch (ex: ClassCastException) {
-            logger().error("Cannot access JNDI resources.", ex)
+            logger.error("Cannot access JNDI resources.", ex)
             null
         }
 
         dataSource?.let { checkConnection(it, dbSchema) }
 
         sc.setAttribute(SC_ATTR_NAME, this)
-        logger().info("Database facade injected into ServletContext.")
+        logger.info("Database facade injected into ServletContext.")
     }
 
     override fun contextDestroyed(sce: ServletContextEvent?) {
--- a/src/main/kotlin/de/uapcore/lightpit/Logging.kt	Sun Dec 12 18:16:46 2021 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,33 +0,0 @@
-/*
- * Copyright 2021 Mike Becker. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-package de.uapcore.lightpit
-
-import org.slf4j.Logger
-import org.slf4j.LoggerFactory
-
-interface LoggingTrait
-
-inline fun <reified T : LoggingTrait> T.logger(): Logger = LoggerFactory.getLogger(T::class.java)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/main/kotlin/de/uapcore/lightpit/MyLogger.kt	Wed Dec 15 19:56:05 2021 +0100
@@ -0,0 +1,65 @@
+/*
+ * Copyright 2021 Mike Becker. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package de.uapcore.lightpit
+
+import java.util.logging.Level
+import java.util.logging.Logger
+
+class MyLogger {
+    private val logger: Logger = Logger.getLogger("de.uapcore.lightpit.Logger")
+
+    fun info(fmt: String, vararg args: Any?) {
+        logger.log(Level.INFO, fmt, args)
+    }
+    fun debug(fmt: String, vararg args: Any?) {
+        logger.log(Level.FINE, fmt, args)
+    }
+    fun warn(fmt: String, vararg args: Any?) {
+        logger.log(Level.WARNING, fmt, args)
+    }
+    fun error(fmt: String, vararg args: Any?) {
+        logger.log(Level.SEVERE, fmt, args)
+    }
+    fun trace(fmt: String, vararg args: Any?) {
+        logger.log(Level.FINEST, fmt, args)
+    }
+
+    fun info(msg: String, ex: Throwable) {
+        logger.log(Level.INFO, msg, ex)
+    }
+    fun debug(msg: String, ex: Throwable) {
+        logger.log(Level.FINE, msg, ex)
+    }
+    fun warn(msg: String, ex: Throwable) {
+        logger.log(Level.WARNING, msg, ex)
+    }
+    fun error(msg: String, ex: Throwable) {
+        logger.log(Level.SEVERE, msg, ex)
+    }
+    fun trace(msg: String, ex: Throwable) {
+        logger.log(Level.FINEST, msg, ex)
+    }
+}
--- a/src/main/kotlin/de/uapcore/lightpit/servlet/ProjectServlet.kt	Sun Dec 12 18:16:46 2021 +0100
+++ b/src/main/kotlin/de/uapcore/lightpit/servlet/ProjectServlet.kt	Wed Dec 15 19:56:05 2021 +0100
@@ -25,8 +25,11 @@
 
 package de.uapcore.lightpit.servlet
 
-import de.uapcore.lightpit.*
+import de.uapcore.lightpit.AbstractServlet
+import de.uapcore.lightpit.HttpRequest
+import de.uapcore.lightpit.boolValidator
 import de.uapcore.lightpit.dao.DataAccessObject
+import de.uapcore.lightpit.dateOptValidator
 import de.uapcore.lightpit.entities.*
 import de.uapcore.lightpit.types.IssueCategory
 import de.uapcore.lightpit.types.IssueStatus
@@ -533,7 +536,7 @@
                         dao.updateComment(comment)
                         dao.insertHistoryEvent(issue, comment)
                     } else {
-                        logger().debug("Not updating comment ${comment.id} because nothing changed.")
+                        logger.debug("Not updating comment ${comment.id} because nothing changed.")
                     }
                 } else {
                     http.response.sendError(403)
@@ -592,7 +595,7 @@
                     dao.updateIssue(issue)
                     dao.insertHistoryEvent(issue)
                 } else {
-                    logger().debug("Not updating issue ${issue.id} because nothing changed.")
+                    logger.debug("Not updating issue ${issue.id} because nothing changed.")
                 }
 
                 val newComment = http.param("comment")
--- a/src/main/kotlin/de/uapcore/lightpit/servlet/UsersServlet.kt	Sun Dec 12 18:16:46 2021 +0100
+++ b/src/main/kotlin/de/uapcore/lightpit/servlet/UsersServlet.kt	Wed Dec 15 19:56:05 2021 +0100
@@ -25,7 +25,10 @@
 
 package de.uapcore.lightpit.servlet
 
-import de.uapcore.lightpit.*
+import de.uapcore.lightpit.AbstractServlet
+import de.uapcore.lightpit.HttpRequest
+import de.uapcore.lightpit.ValidatedValue
+import de.uapcore.lightpit.ValidationError
 import de.uapcore.lightpit.dao.DataAccessObject
 import de.uapcore.lightpit.entities.User
 import de.uapcore.lightpit.viewmodel.UserEditView
@@ -33,7 +36,7 @@
 import javax.servlet.annotation.WebServlet
 
 @WebServlet(urlPatterns = ["/users/*"])
-class UsersServlet : AbstractServlet(), LoggingTrait {
+class UsersServlet : AbstractServlet() {
 
     init {
         get("/", this::index)
@@ -91,7 +94,6 @@
         }
 
         if (user.id > 0) {
-            logger().info("Update user with id ${user.id}.")
             dao.updateUser(user)
             http.renderCommit("users/")
         } else {
@@ -103,7 +105,6 @@
             }, "", errorMessages)
 
             if (errorMessages.isEmpty()) {
-                logger().info("Insert user ${user.username}.")
                 dao.insertUser(user)
                 http.renderCommit("users/")
             } else {

mercurial