DEV Community

Cover image for Clojure Is Awesome!!! [PART 2]
André Borba
André Borba

Posted on

Clojure Is Awesome!!! [PART 2]

From the series 'I don't need to say anything... :)

(ns singleton)

(defprotocol LoggerService
  "Protocol defining logging operations."
  (log-info [this message] "Logs an informational message.")
  (log-error [this message] "Logs an error message.")
  (log-debug [this message] "Logs a debug message."))

(defrecord FileLogger [log-file]
  LoggerService
  (log-info [_ message]
    (spit log-file (str (java.time.Instant/now) " [INFO]: " message "\n") :append true))
  (log-error [_ message]
    (spit log-file (str (java.time.Instant/now) " [ERROR]: " message "\n") :append true))
  (log-debug [_ message]
    (spit log-file (str (java.time.Instant/now) " [DEBUG]: " message "\n") :append true)))

(defonce logger-instance
  (atom nil))

(defn get-logger
  "Returns the singleton instance of the LoggerService."
  []
  (if-let [instance @logger-instance]
    instance
    (let [new-instance (->FileLogger "application.log")]
      (reset! logger-instance new-instance)
      new-instance)))

(defn log-endpoint
  "A Pedestal handler that logs requests and responses."
  [request]
  (let [logger (get-logger)]
    (log-info logger (str "Received request: " (:uri request)))
    {:status 200
     :body   "Request logged successfully!"}))

(require '[io.pedestal.http :as http])

(def service
  {:env                  :prod
   ::http/routes         #{["/log" :get log-endpoint]}
   ::http/type           :jetty
   ::http/port           8080})

(comment
  ;; Start the server
  (http/create-server service)
  ;; curl http://localhost:8080/log
)

Enter fullscreen mode Exit fullscreen mode

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

Use Playwright to test. Use Playwright to monitor.

Join Vercel, CrowdStrike, and thousands of other teams that run end-to-end monitors on Checkly's programmable monitoring platform.

Get started now!

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay