If we google this question we get Sage Vyasa as answer and that what I have learned growing up. But Shri Krishna gave this knowledge to Arjuna only, and there so on one else there who was writing that down. Sanjay was only relaying the information to Dritharashtra. Sage Vyasa was not anywhere near Kurukshetra then how would he knew exact words of Lord Krishna and wrote that down?
Like in Ramayana, Sage Valmiki had boon of seeing everything that was going to happen and he wrote it down and this was also mentioned in Ramayana.
Also when was it written, after it all happened or before (like in Ramayana)?