CodeTrek
CodeTrek

Reputation: 475

Prepending time stamp to stdout

I am having a datetime suffix appended to my stdout for logging reasons in my application.

old_f = sys.stdout
class F:
    def write(self, x):
        old_f.write(x.replace("\n", " [%s]\n" % str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))))
    def flush(self):
        pass
sys.stdout = F()

>x = "World!"
>print("Hello " + x)
>Hello world! [2022-05-23 02:15:34]

This does the job, but I can't for the sake of it prepend the timestamp to the string, eg:

>x = "World!"
>print("Hello " + x)
>[2022-05-23 02:15:34] Hello world

I tried the regular tricks, joining, indexing etc. but the strange thing is that the time index string gets multiple times appended in between the arguments and not only in the beginning of the stdout line.

Upvotes: 1

Views: 718

Answers (1)

asymptote
asymptote

Reputation: 1402

Since print() function calls sys.stdout.write() twice for each output, a workaround would be to add a condition to check if x is not "\n".

old_f = sys.stdout
class F:
    def write(self, x):
        if x != "\n":
            dt_str =str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
            x = f"[{dt_str}] {x}"
        old_f.write(x)

    def flush(self):
        pass
sys.stdout = F()

x = "World!"
print("Hello " + x)

This will not work with more than 1 arguments to print(). In other words, concatenate all strings to be printed and pass 1 single string to print(). You can also do len(x) > 1 check in case all arguments have more than 1 characters. In this case, you may pass more than 1 arguments, granted none of thise arguments are \n.

Upvotes: 1

Related Questions