GoGym!

Here am I, holding a cup of coffee, again, thinking in a new project that I could create, and I don't know  what to do, not yet. I'm checking my last code looking for new ideas and, that's it!. I'm going to finish my cup of coffee and later, I will start to write code.

OK, now is later! 😂

My last code it's so simple, an API Rest that is publish in a localhost and show default data (obtain IP address automatically 😉). To upgrade the code, I could get data from Postgrest Database, creating a connection module. Does it work? of course, investigating and learning more about Golang obviously, and .... Can I create a Config file and remove from the code some parameters?

yes, I can and is much better than before, which means that now I must create a new module to read the config file 👨‍💻.

I take a relax position, stretch my fingers and I think... I need to make debug, I need a log file but, which module can I use? good, interesting and great challenge! 💪🏻 I'll create my own logger.

What I need?

  1. It should be simple to use.
  2. It should be configurable.
  3. It should rotate by size and keep X backup file.
  4. It should write fast! and to manage queues (lock)
  5. One or more processes could write the same file or another

easy peasy lemon squeezy!....  hmmmmm, I don't think so 😂

To do it simple, I'll develop a basic and functional Logger module that just need the name of log file, path and level to start.

 Log.Start("nGR1.log", "/var/log", "DEBUG")

Now and after that the development is finished, the module will start like this. The rest of the parameters are considered as default values, in order to keep the simplicity.

I create a struct that contains all the necessary to configure an instance of the Logger.

Is it the correct way to do it? I don't known. It is what I need, though.

To configure the rotations, I created the method Rotationwhich can be used or not.

The rotation receives two parameters: SizeMB and Backup, where the first is the size in megabytes that the file must have before the rotation and the second is the number of files you want to save as backup. Does it work?

it works perfectly!

To resolve concurrency in write, I use channel because my own queues were not fast, I need to learn more about that. I added the lock function (Go's standard library provides mutual exclusion with sync.Mutex) to resolve concurrency, keeping the file locked while some process is writing or the logger is rotating.

Finally,  the Logger is alive! ready to use and I'm so excited to read your comments. If you want to know how I do it or how can you use it, just click on the button "Logger Project".

 

Leave a Comment