Home > Net >  Insert text to a file between before or after a certain line
Insert text to a file between before or after a certain line

Time:11-15

Here is my function to add a message to my log file

func Glogger(prefix string, message string) {
    file, err := os.OpenFile("glogger.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        log.Println(err)
    }

    defer file.Close()

    logger := log.New(file, prefix " : ", log.LstdFlags)
    logger.Println(message)
}

This will append a new line in my log file. But I want to add my message above the gopher's head and always keep my gopher at the bottom of my file like this:

enter image description here

It's possible to add a new line after a log message or before a specific character like the top of the gopher's head .:-== =-: ?

If it's not possible there is a way to count the x lines from the end of the file and start to write by setting an offset ?

Or can we delete the gopher, append the new log and then recreate the gopher ?

CodePudding user response:

I solved my problem. Thanks to the commenters who shows me the way.

  • I measured my gopher byte size
  • I create a temp log file
  • I copy the total byte size of the main log file into the temp file while I substract the gopher byte size
  • I append my log error and I draw the gopher at the end of the file

Here is my code :

import (
    "io"
    "log"
    "os"
)

const gopherSize = 1934
const gloggerFile = "glogger.log"
const tmpFile = "tmp.log"

func Glogger(prefix string, message string) {
    // Create temp file
    tmp, err := os.Create(tmpFile)
    if err != nil {
        panic(err)
    }

    defer tmp.Close()

    // Check if glogger file exists open and copy until the gopher
    // to the temp file
    if _, err := os.Stat(gloggerFile); err == nil {
        glogger, err := os.Open(gloggerFile)
        if err != nil {
            panic(err)
        }

        defer glogger.Close()

        totalBytes, err := glogger.Stat()
        if err != nil {
            panic(err)
        }

        io.CopyN(tmp, glogger, totalBytes.Size()-gopherSize)
    }

    logger := log.New(tmp, prefix " : ", log.LstdFlags)
    logger.Println(message)

    drawGoopher()
    replaceTmpFile()
}

func replaceTmpFile() {
    if _, err := os.Stat(gloggerFile); err == nil {
        if err := os.Remove(gloggerFile); err != nil {
            panic(err)
        }
    }

    if err := os.Rename(tmpFile, gloggerFile); err != nil {
        panic(err)
    }
}

func drawGoopher() {
    file, err := os.OpenFile(tmpFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        panic(err)
    }

    file.WriteString(`

                         .:-==                     =-:                  
                    .- ** =-:.                      .:- **=.                    
                 -** :                           .:::.    .=* :.-       -       
    -         -**:   .-::::::-:              :---.   .:--:   . %        -**     
  -#-       :#=   .--.        .--:         -=.            --    =#. .     -#    
 -%     ..  #.   --              :=        .               .     .%@@@=    #-   
 #-     @@@      .                       =. :==-.            =     #@@-    *=   
 *     -@@=    . .*@@@%-           :-      #@@@@@-           =      #     -%    
 .%-    *      --#@@@@*@           .      .@@@@=-            =       %: -*      
    #=.-%      .*-%@@%==           -:    :-.*%%*-           .=       -@*-       
     :=@-       :- .::            .=      :-               :=         #=        
      .%         :=.             --.=*###*-.--.          :-:          .%        
       *           :--:      .--- :@@@@@@@@   :----------              #-       
      %-               ::::::.  --:-*#%%%*-.--:                         *       
     .@:                       =              .=                       -%       
     .@.                       =     :---.     =                       :@       
     :@                         :::*:    .- ::-                        .@.      
     -@                            =       -.                           @.      
     :@                           .=   #   -.                           @:      
     .@.                           -::-:=::-                            @:      
      @:                                                                @:      
      #=                                                                @:      
      =*                                                                @:      
       %                                                                @:   `)

}

I'm sure there is a better way to do that but it does the job

  • Related