Factually you ask two different things, "how" and "why", and maybe considering the "how" first makes things clearer.
Obviously, the FIDE time control is recent. In early history of chess there was no time control at all, the problem with that should be obvious. I am old enough to have played 40 moves/2 hours + adjournment, thus it's more recent than you might think.
Now to the "why". There is nothing special with 40 moves or two hours. Clearly 41 moves would be silly, man automatically thinks in round numbers. I daresay (experienced from thousands of tournament games, and only judging from the time spent by my opponents - I'm a notorical "blitzer") that 30 moves are too short: the hectic of time trouble would hit the midst of a game. 50 moves are too long - we are in the endgame already and could as well play it out. The same holds for "2 hours" which is not as carved in stone as you might think, I played lot of games in lower leagues with shorter, and also in higher with two time controls (40/2h+20/1h+rest/30m).
That said, the standard time control before the invention of electronic chess clocks was just a rounded compromise - almost anyone could live with it. Nowadays, indeed almost all games (at least the "top" ones) are played with Fischer bonus, which admittedly has advantages, especially for the referees (I'm one too and can acknowledge that).
tl;dr: No logic, just evolution, which includes clinging to accustomed numbers. If chess would be invented today, one might converge to another time control.