You have put your finger on one of the incongruous features in this otherwise standard Shakespearian comedy. Malvolio is the one aspects that jarrs when compared to the rest of the merriment, and it is fascinating to trace the development of his character from start to finish.
Malvolio when we first meet him seems to be a figure of fun for other characters. They mock his pompous, self-important attitude and Maria and Sir Toby take great delight in plotting his downfall, focussing on using his own ambitions against him by encouraging him to believe what he secretly hopes for: that Olivia loves him and he has a chance of marrying her. We all enjoy the famous "yellow stockings" scene of Act III scene 4, and in a sense, when Olivia says, "Why this is very midsummer madness!" in response to Malvolio´s overtures she identifies an important theme in the story: love is as a sickness or a disease that comes upon us suddenly and makes us act out of character and do stupid things.
Yet whilst we laugh at Malvolio in his yellow cross-gartered stockings trying to smile at Olivia, what happens next upsets this simple mockery of his character. In Act IV scene 2, when Feste dressed as Sir Topas goads Malvolio and tries to make him think he is mad, we see a very different side to Malvolio, and begin to respect and pity him. Malvolio´s stubborn determination to hold on to his sanity and his protestations that he is not mad, in spite of Feste´s many linguistic tricks to prove otherwise is something that we come to admire. Despite all his sufferings and being locked up in the dark, he is still able to say to Feste in response to being asked if he is mad:
Believe me, I am not. I tell thee true.
Shakespeare seems to bestow on Malvolio a certain dignity and gravitas in the face of suffering that stands in sharp contrast to the rest of the light-hearted comedy of the play. Whilst he represents a force of order that needs to be "locked away" so the other characters can enjoy the revels, confusion and chaos of this festival of Twelfth Night, his punishment is disporportionate to his crime, as Maria and Sir Toby recognise. Their act of fleeing the anticipated wrath of Olivia shows they realise they have gone too far. Malvolio is re-admitted into the company at the end of the play, but has no part in their celebrations. His final word before leaving:
I´ll be revenged on the whole pack of you!
strikes a very discordant note in an otherwise traditional happy ending to a comedy. Even though Orsino orders men to go after him and "entreat him to peace" we are left slightly uncomfortable with this ending as the marriage celebrations begin.