Get one or two heavy hardwood timbers, like railway sleeper size and chain to tracks, obviously before you've buried them. Drive forward pulling the timber under the tracks and lifting the machine and moving it forward free of the sand/swamp/mud. Additional timbers as bog mats can be laid for the machine to continue to drive forward on.
This assumes the machine is in working order and can drive the tracks. Any steel tracked machine, excavator, dozer etc can be unbogged this way with the right gear. It should be even easier with an excavator where you can pull and push with the bucket.
But as has been mentioned as soon as the machine starts to get bogged is the time to take action. And don't get me started on the idiots that seem to believe the way out of any bog situation is to give the machine/vehicle full revs and spin the wheels/tracks, immediately digging the machine deeper
Every movement of the tracks, revolution of the wheel should be freeing the machine. If it isn't then stop, you're doing it wrong, and you'll make things worse.