在特定行之前或之后将文本插入文件中

huangapple go评论77阅读模式
英文:

Insert text to a file between before or after a certain line

问题

这是我用来将消息添加到日志文件的函数:

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)
}

这将在我的日志文件中追加一行。但是我想要将我的消息添加到地鼠头部的上方,并始终保持地鼠位于文件底部,像这样:

在特定行之前或之后将文本插入文件中

是否可以在日志消息之后或者在地鼠头部上方的特定字符之前添加一个新行,比如 .:-==+++++++++++++++++++++=-:

如果不可能的话,是否有一种方法可以从文件末尾计算出 x 行,并通过设置偏移量开始写入?

或者我们可以删除地鼠,追加新的日志,然后重新创建地鼠吗?

英文:

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:

在特定行之前或之后将文本插入文件中

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 ?

答案1

得分: 0

我解决了我的问题。感谢那些给我指路的评论者。

  • 我测量了我的地鼠字节大小
  • 我创建了一个临时日志文件
  • 我将主日志文件的总字节大小拷贝到临时文件中,同时减去地鼠字节大小
  • 我在文件末尾添加了我的日志错误,并绘制了地鼠

以下是我的代码:

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

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

func Glogger(prefix string, message string) {
	// 创建临时文件
	tmp, err := os.Create(tmpFile)
	if err != nil {
		panic(err)
	}

	defer tmp.Close()

	// 检查 glogger 文件是否存在,打开并将地鼠之前的内容拷贝到临时文件中
	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(`

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

}

我相信有更好的方法来实现这个但这个代码已经能够完成工作了

<details>
<summary>英文:</summary>

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 (
    	&quot;io&quot;
    	&quot;log&quot;
    	&quot;os&quot;
    )

    const gopherSize = 1934
    const gloggerFile = &quot;glogger.log&quot;
    const tmpFile = &quot;tmp.log&quot;
    
    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+&quot; : &quot;, 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&#39;m sure there is a better way to do that but it does the job

</details>



huangapple
  • 本文由 发表于 2021年11月11日 23:19:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/69930742.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定