<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Amjad Nazar on Medium]]></title>
        <description><![CDATA[Stories by Amjad Nazar on Medium]]></description>
        <link>https://medium.com/@amjadnzr?source=rss-6e740090b4e5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MlHYNHjmyVrSC11KbAzXRw.jpeg</url>
            <title>Stories by Amjad Nazar on Medium</title>
            <link>https://medium.com/@amjadnzr?source=rss-6e740090b4e5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 17:05:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amjadnzr/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Implementing a Custom Logger for Go Fiber Application with Logrus]]></title>
            <link>https://medium.com/@amjadnzr/implementing-a-custom-logger-for-go-fiber-application-with-logrus-f451ca7b2dbd?source=rss-6e740090b4e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f451ca7b2dbd</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[log-files]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[logging]]></category>
            <dc:creator><![CDATA[Amjad Nazar]]></dc:creator>
            <pubDate>Thu, 16 Jan 2025 18:55:24 GMT</pubDate>
            <atom:updated>2025-01-16T19:03:32.265Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*weVjmEycAiIwnvbDy7Rf7Q.jpeg" /></figure><p>In a recent project, I was exploring how to build a logger that would fit my needs. This blog is based on the lessons I learned while implementing logging for a Go Fiber application.</p><p>When you start building a logger, the first thing to think about is what you want to log. Depending on your project’s domain, security needs, and what information is important for tracking and debugging in production, you’ll need to decide what to include in your logs. In some projects, the logger might only record errors, while in others, it could log requests and responses.</p><p>In this implementation I have considered to the following data:</p><ul><li><strong>TraceId / RequestId</strong>: An Id to track and group logs for each request.</li><li><strong>Date and Time</strong>: Timestamp for the log entry.</li><li><strong>Log Level</strong>: Whether it’s an info, warning, or error message.</li><li><strong>Request / Response</strong>: Information about the request and the response.</li><li><strong>Response Status</strong>: The status code of the response.</li></ul><p>You can improve on this by selectively logging requests or ignoring the body altogether, depending on your project. Additionally, other useful information you might want to log includes:</p><ul><li><strong>Service Name / File Name</strong>: Where the error occurred.</li><li><strong>Process Id</strong>: The ID of the running process.</li><li><strong>Context Data</strong>: For example, User ID, User IP Address, etc.</li></ul><p>Let’s now dive into building the application.</p><h3>Prerequisites</h3><p>To get started, initialise your project as a Go module and install the required packages:</p><pre>go get github.com/gofiber/fiber/v2<br>go get github.com/sirupsen/logrus</pre><h4>Logger Implementation</h4><p>Create a new file: /internal/logger/logger.go</p><pre>package logger<br><br>import (<br> &quot;fmt&quot;<br> &quot;path/filepath&quot;<br><br> &quot;io&quot;<br> &quot;os&quot;<br> &quot;strings&quot;<br> &quot;time&quot;<br><br> &quot;github.com/gofiber/fiber/v2&quot;<br> &quot;github.com/sirupsen/logrus&quot;<br>)<br><br>type ILoggerSetup interface {<br>   GetApiLogger(c *fiber.Ctx) *logrus.Entry<br>}<br><br>type LoggerSetup struct {<br>   logrusLogger *logrus.Logger<br>   env          string<br>}<br><br>func (ls *LoggerSetup) GetApiLogger(c *fiber.Ctx) *logrus.Entry {<br>   now := time.Now().Format(&quot;2006-01-02&quot;)<br>  <br>   logFileName := fmt.Sprintf(&quot;logs/app_%s.log&quot;, now)<br>  <br>   logDir := filepath.Dir(logFileName)<br>  <br>   if err := os.MkdirAll(logDir, os.ModePerm); err != nil {<br>       ls.logrusLogger.SetOutput(io.Writer(os.Stdout))<br>   } else {<br>       logFile, err := os.OpenFile(logFileName, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)<br>    if err == nil {<br>       ls.logrusLogger.SetOutput(io.MultiWriter(os.Stdout, logFile))<br>    } else {<br>       ls.logrusLogger.SetOutput(io.Writer(os.Stdout))<br>    }<br>   }<br>  <br>   requestId := c.Locals(&quot;requestId&quot;)<br>  <br>   return ls.logrusLogger.WithFields(logrus.Fields{<br>      &quot;requestId&quot;: requestId,<br>      &quot;status&quot;:    c.Response().StatusCode(),<br>      &quot;method&quot;:    c.Method(),<br>      &quot;path&quot;:      c.Path(),<br>   })<br>}<br><br>type customFormatter struct{}<br><br>func (f *customFormatter) Format(entry *logrus.Entry) ([]byte, error) {<br><br>   logLine := fmt.Sprintf(&quot;[%s] | [%s] -  Request Id : %s | %s | %d | %s | %s \n&quot;, entry.Time.Format(&quot;2006-01-02 15:04:05&quot;), strings.ToUpper(entry.Level.String()),<br>    entry.Data[&quot;requestId&quot;], entry.Data[&quot;method&quot;], entry.Data[&quot;status&quot;], entry.Data[&quot;path&quot;], entry.Message)<br>   return []byte(logLine), nil<br>}<br><br>func New(env string) ILoggerSetup {<br>   logrusLogger := logrus.New()<br>   logrusLogger.SetFormatter(&amp;customFormatter{})<br>  <br>   if env == &quot;prod&quot; {<br>    logrusLogger.SetLevel(logrus.InfoLevel)<br>   } else {<br>    logrusLogger.SetLevel(logrus.DebugLevel)<br>   }<br>  <br>   return &amp;LoggerSetup{<br>    logrusLogger: logrusLogger,<br>    env:          env,<br>   }<br>}</pre><p>In this code block, I have created the LoggerSetup struct, which embeds the logrus logger package&#39;s implementation. This struct also implements the ILoggerSetup interface.</p><p>The custom Formatter struct is designed to implement the logrus.Formatter interface, where the Format function defines how the log message is formatted. You can further customise the output by adding more data to the return string.</p><p>Additionally, the logger is set up to log both to the console and a log file. The code ensures that a new log file is created each day inside the logs folder.</p><p>Next, let’s implement a global-level application context to initialise the logger, making it accessible throughout the entire project.</p><h4>Initialise the Global Context</h4><p>Create another file: /appContext/app-context.go</p><pre>package appContext<br><br>import (<br>   logger &quot;github.com/amjadnzr/go-custom-logger-implementation/internal/logger&quot;<br>   &quot;github.com/gofiber/fiber/v2&quot;<br>   &quot;github.com/sirupsen/logrus&quot;<br>)<br><br>type IAppContext interface {<br>   GetApiLogger(c *fiber.Ctx) *logrus.Entry<br>}<br><br>type AppContext struct {<br>   loggerSetup logger.ILoggerSetup<br>}</pre><p>In this part, we include the logger setup reference within the AppContext, which will be initialized when the application starts. This allows the logger to be easily accessed throughout the application.</p><p>Next, create another file, /appContext/app-context.go, where we&#39;ll initialise the global application context and wire everything together.</p><pre>package appContext<br><br>import (<br>   logger &quot;github.com/amjadnzr/go-custom-logger-implementation/internal/logger&quot;<br>   &quot;github.com/gofiber/fiber/v2&quot;<br>   &quot;github.com/sirupsen/logrus&quot;<br>)<br><br>var appContext *AppContext<br><br>func GetGlobalContext() IAppContext {<br>   return appContext<br>}<br><br>func InitGlobalAppContext(env string) IAppContext {<br>   appContext = &amp;AppContext{<br>      loggerSetup: logger.New(env),<br>   }<br><br>   return appContext<br>}<br><br>func (ac *AppContext) GetApiLogger(c *fiber.Ctx) *logrus.Entry {<br>   return ac.loggerSetup.GetApiLogger(c)<br>}</pre><p>In this piece of code, I’ve included the logic to initialize the logger when we set up the application context at runtime.</p><h3>Main Application</h3><p>Now, let’s create the main.go file and run the application</p><pre>package main<br><br>import (<br>   &quot;github.com/amjadnzr/go-custom-logger-implementation/appContext&quot;<br>   middlewares &quot;github.com/amjadnzr/go-custom-logger-implementation/middleware&quot;<br>   &quot;github.com/gofiber/fiber/v2&quot;<br>)<br><br>func main() {<br>   app := fiber.New()<br>  <br>   appContext.InitGlobalAppContext(&quot;dev&quot;)<br><br>   app.Get(&quot;/ping&quot;, func(c *fiber.Ctx) error {<br>  <br>      logger := appContext.GetGlobalContext().GetApiLogger(c)<br>      logger.Info(&quot;hello&quot;)<br>    <br>      return c.SendString(&quot;pong&quot;)<br>   })<br>  <br>   if err := app.Listen(&quot;:8080&quot;); err != nil {<br>      panic(err)<br>   }<br>}</pre><p>In the main.go file, I have initialized the global app context and used the logger, as demonstrated in the previous implementation. Run the following commands:</p><ol><li>Execute go mod tidy to clean up the dependencies.</li><li>Run the application with go run .and visit http://localhost:8080/ping in your browser. You should see the response message &quot;pong&quot;.</li></ol><p>Afterward, check your project directory, and you’ll find a new folder named “logs” that contains the log records.</p><h4>Logger Middleware</h4><p>Next, we can extend this setup by adding a logger middleware to log both the request and response. Let’s start by creating a new file called /middleware/logger-middleware.go</p><pre>package middlewares<br><br>import (<br>   &quot;fmt&quot;<br>  <br>   &quot;github.com/amjadnzr/go-custom-logger-implementation/appContext&quot;<br>   &quot;github.com/gofiber/fiber/v2&quot;<br>   &quot;github.com/google/uuid&quot;<br>)<br><br>func Logger() func(ctx *fiber.Ctx) error {<br>   return func(ctx *fiber.Ctx) error {<br>  <br>      requestId := uuid.New().String()<br>      ctx.Locals(&quot;requestId&quot;, requestId)<br>    <br>      globalCtx := appContext.GetGlobalContext()<br>      logger := globalCtx.GetApiLogger(ctx)<br>    <br>      logTxt := &quot;Request received&quot;<br>      query := string(ctx.Request().URI().QueryString())<br>      if query != &quot;&quot; {<br>         logTxt = logTxt + fmt.Sprintf(&quot; | Query : %s &quot;, ctx.Context().QueryArgs())<br>      }<br>    <br>      if len(ctx.Body()) != 0 {<br>         logTxt = logTxt + fmt.Sprintf(&quot; | Body: %s&quot;, ctx.Body())<br>      }<br>    <br>      logger.Info(logTxt)<br>    <br>      err := ctx.Next()<br>    <br>      if err != nil {<br>         logger.Error(&quot;Error: &quot;, err.Error())<br>         return err<br>      }<br>    <br>      resBody := string(ctx.Response().Body())<br>      if len(resBody) != 0 {<br>         logger.Info(&quot;Responded: &quot;, resBody)<br>         return nil<br>      }<br>    <br>      logger.Info(&quot;Responded: &quot;)<br>    <br>      return nil<br>  }<br>}</pre><p>This code snippet handles logging for the request, response, and any errors that may occur. After implementing the logger middleware, you’ll need to include it in the Fiber app. To do this, go to the main.go file, and inside the main function, add the following line after the fiber app object initialiation:</p><pre>app.Use(middlewares.Logger())</pre><p>Once you’ve made the changes, run the app as before. You should see the output in both the console and the log file, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qzt6ahjsyDksujSZExW57w.png" /><figcaption>Screenshot of the log file.</figcaption></figure><p>That’s all I have to share for now. I hope you found something useful in this blog. I’ll be back soon with another post, so feel free to connect, leave comments, share suggestions, and follow my profile to stay updated on my upcoming blogs.</p><p>Thank you, and take care!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f451ca7b2dbd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing a Generic Repository Layer for MongoDB in Go]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://levelup.gitconnected.com/implementing-a-generic-repository-layer-for-mongodb-in-go-cf88a30ea38d?source=rss-6e740090b4e5------2"><img src="https://cdn-images-1.medium.com/max/1792/1*6hqxxqFPSi8jYNXUxxgGEA.jpeg" width="1792"></a></p><p class="medium-feed-snippet">Recently, in one of my projects, I implemented the repository layer using generics in Go. In this blog, I want to share how I implemented&#x2026;</p><p class="medium-feed-link"><a href="https://levelup.gitconnected.com/implementing-a-generic-repository-layer-for-mongodb-in-go-cf88a30ea38d?source=rss-6e740090b4e5------2">Continue reading on Level Up Coding »</a></p></div>]]></description>
            <link>https://levelup.gitconnected.com/implementing-a-generic-repository-layer-for-mongodb-in-go-cf88a30ea38d?source=rss-6e740090b4e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf88a30ea38d</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[repository-design-pattern]]></category>
            <category><![CDATA[generics]]></category>
            <dc:creator><![CDATA[Amjad Nazar]]></dc:creator>
            <pubDate>Mon, 13 Jan 2025 19:25:55 GMT</pubDate>
            <atom:updated>2025-01-15T15:06:08.951Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[A First Look into Concurrency in Go]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://towardsdev.com/a-first-look-into-concurrency-in-go-c744e4fff14d?source=rss-6e740090b4e5------2"><img src="https://cdn-images-1.medium.com/max/1707/1*pPx2qn_0SZElnpoCnhQzVA.png" width="1707"></a></p><p class="medium-feed-link"><a href="https://towardsdev.com/a-first-look-into-concurrency-in-go-c744e4fff14d?source=rss-6e740090b4e5------2">Continue reading on Towards Dev »</a></p></div>]]></description>
            <link>https://towardsdev.com/a-first-look-into-concurrency-in-go-c744e4fff14d?source=rss-6e740090b4e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/c744e4fff14d</guid>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[goroutines]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Amjad Nazar]]></dc:creator>
            <pubDate>Sun, 16 Jan 2022 13:12:36 GMT</pubDate>
            <atom:updated>2025-01-13T20:38:15.191Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[From a Night Owl to an Early Bird, Good Move ?]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@amjadnzr/from-a-night-owl-to-an-early-bird-good-move-90195b730f1a?source=rss-6e740090b4e5------2"><img src="https://cdn-images-1.medium.com/max/2600/0*GBjVqwhkAbV-3py7" width="4032"></a></p><p class="medium-feed-snippet">This blog is regarding my experiment of changing my sleep pattern from an evening person to morning person. I&#x2019;ll be discussing why and how&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@amjadnzr/from-a-night-owl-to-an-early-bird-good-move-90195b730f1a?source=rss-6e740090b4e5------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@amjadnzr/from-a-night-owl-to-an-early-bird-good-move-90195b730f1a?source=rss-6e740090b4e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/90195b730f1a</guid>
            <category><![CDATA[organize]]></category>
            <category><![CDATA[morning]]></category>
            <category><![CDATA[sleep]]></category>
            <category><![CDATA[life]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Amjad Nazar]]></dc:creator>
            <pubDate>Tue, 11 Aug 2020 01:31:41 GMT</pubDate>
            <atom:updated>2020-10-09T19:01:45.382Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Three steps to consider while solving a software engineering problem]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://levelup.gitconnected.com/three-steps-to-consider-while-solving-a-software-engineering-problem-6f865ced4e00?source=rss-6e740090b4e5------2"><img src="https://cdn-images-1.medium.com/max/2600/0*UhU9esbWC8rzIwVB" width="7890"></a></p><p class="medium-feed-snippet">I am writing this blog with the experience I had gained through my one year long internship at Aeturnum. At the beginning weeks of my&#x2026;</p><p class="medium-feed-link"><a href="https://levelup.gitconnected.com/three-steps-to-consider-while-solving-a-software-engineering-problem-6f865ced4e00?source=rss-6e740090b4e5------2">Continue reading on Level Up Coding »</a></p></div>]]></description>
            <link>https://levelup.gitconnected.com/three-steps-to-consider-while-solving-a-software-engineering-problem-6f865ced4e00?source=rss-6e740090b4e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f865ced4e00</guid>
            <category><![CDATA[experience-learning]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-internship]]></category>
            <category><![CDATA[software-problems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Amjad Nazar]]></dc:creator>
            <pubDate>Sat, 11 Jul 2020 01:53:12 GMT</pubDate>
            <atom:updated>2020-09-03T12:30:01.998Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Creating a Custom Logger for a Node.js Application using Winston]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://levelup.gitconnected.com/creating-a-custom-logger-for-node-js-application-using-winston-3925007c9659?source=rss-6e740090b4e5------2"><img src="https://cdn-images-1.medium.com/max/1826/1*0MOGVmOgWmfVdPG0g6arYA.png" width="1826"></a></p><p class="medium-feed-snippet">A guide to building a custom logger from scratch in Node</p><p class="medium-feed-link"><a href="https://levelup.gitconnected.com/creating-a-custom-logger-for-node-js-application-using-winston-3925007c9659?source=rss-6e740090b4e5------2">Continue reading on Level Up Coding »</a></p></div>]]></description>
            <link>https://levelup.gitconnected.com/creating-a-custom-logger-for-node-js-application-using-winston-3925007c9659?source=rss-6e740090b4e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/3925007c9659</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[winston]]></category>
            <category><![CDATA[log-files]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Amjad Nazar]]></dc:creator>
            <pubDate>Sun, 24 Nov 2019 16:15:34 GMT</pubDate>
            <atom:updated>2019-12-02T21:13:00.890Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Adding and Updating data  in csv file via Flask API]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/swlh/adding-and-updating-data-in-csv-file-via-flask-api-252babbc6381?source=rss-6e740090b4e5------2"><img src="https://cdn-images-1.medium.com/max/1835/1*k3d1ELPAUNsnAqon2mnWzQ.png" width="1835"></a></p><p class="medium-feed-snippet">This article will take you through how to add and update data in a csv file via flask API. I experienced this while I was doing a group&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/swlh/adding-and-updating-data-in-csv-file-via-flask-api-252babbc6381?source=rss-6e740090b4e5------2">Continue reading on The Startup »</a></p></div>]]></description>
            <link>https://medium.com/swlh/adding-and-updating-data-in-csv-file-via-flask-api-252babbc6381?source=rss-6e740090b4e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/252babbc6381</guid>
            <category><![CDATA[flask-framework]]></category>
            <category><![CDATA[dataset]]></category>
            <category><![CDATA[pandas-dataframe]]></category>
            <category><![CDATA[csv-file]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Amjad Nazar]]></dc:creator>
            <pubDate>Mon, 10 Jun 2019 20:06:41 GMT</pubDate>
            <atom:updated>2019-06-12T21:22:29.550Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Google Authentication for Node js Application using Passport]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/swlh/google-authentication-for-node-js-application-using-passport-678c8c068dd8?source=rss-6e740090b4e5------2"><img src="https://cdn-images-1.medium.com/max/1280/1*Ck1OUfu2TTeYB4B55gDWCQ.png" width="1280"></a></p><p class="medium-feed-snippet">This article will take you through how Google authentication has to be implemented in a Node js application. To do so you will have to&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/swlh/google-authentication-for-node-js-application-using-passport-678c8c068dd8?source=rss-6e740090b4e5------2">Continue reading on The Startup »</a></p></div>]]></description>
            <link>https://medium.com/swlh/google-authentication-for-node-js-application-using-passport-678c8c068dd8?source=rss-6e740090b4e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/678c8c068dd8</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[passportjs]]></category>
            <category><![CDATA[google-oauth]]></category>
            <dc:creator><![CDATA[Amjad Nazar]]></dc:creator>
            <pubDate>Thu, 09 May 2019 06:28:03 GMT</pubDate>
            <atom:updated>2019-11-24T18:18:20.638Z</atom:updated>
        </item>
    </channel>
</rss>