How do I save the key pressed(globally) into a txt file?

I want to save it so that I can read it from the txt file and verify whether to proceed another function or not.

By Global I mean you know, record all key presses in or out of the app(while app running).

I have done this before, but unfortunately, I lost my codes in a hdd crash.