In this paper we define B-Fredholm elements in a Banach algebra A modulo an ideal J of A. When a trace function is given on the ideal J, it generates an index for B-Fredholm elements. In the case of a B-Fredholm operator T acting on a Banach space, we prove that its usual index ind(T) is equal to the trace of the commutator [T, T0], where T0 is a Drazin inverse of T modulo the ideal of finite rank operators, extending Fedosov's trace formula for Fredholm operators (see Böttcher and Silbermann [Analysis of Toeplitz operators, 2nd edn (Springer, 2006)]. In the case of a primitive Banach algebra, we prove a punctured neighbourhood theorem for the index.