Alex Gray, from Perth in Tayside, was convicted of burglary and harassment in April at Harrow Crown Court.
Gray, 31, had started pursuing the star in 2008, sending abusive letters before he was banging on her door and spending nights in her back garden.
He was charged last October when the singer was awoken by him bursting into her bedroom in the early hours.
Lily Allen 'victim-shamed' over stalker
Singer's stalker 'needs help, not jail'
The singer was with her children in the room when he broke in to the flat, forcing her to leave the property for good.
In a victim impact statement read in court the singer said she was "left terrified for my and my children's safety".
She said the presence of another person with her at the time was likely to have scared him off.
Sentencing, Judge Martyn Barklem said the stalker had told police he would "cut her with a knife".
The judge said: "This was a terrifying experience for (Lily Allen), and it was extremely fortunate there was an adult male in the property who evicted Mr Gray from it."
A man who stalked singer Lily Allen for years and broke into her house has been given an indeterminate hospital order.